如何在python中读取嵌套的json数据值?

Posted

技术标签:

【中文标题】如何在python中读取嵌套的json数据值?【英文标题】:How to read nested json data values in python? 【发布时间】:2020-01-28 20:24:26 【问题描述】:

我正在尝试将嵌套的 json 文件读入 python 。它的格式如下 -



"13638": 

    "Advocate Name": "BRET ALLEN",

    "No. of Cases": "2",

    "WP 15699/2019": 

         "Case Category": "SERVICE",

         "District": "HYDERABAD",

         "Filing Date": "23/07/2019",

         "Registration Date": "24/07/2019",

         "Listing Date": "26/08/2019",

         "Case Status": "PENDING"
          ,

    "CRLP 804/2019": 

         "Case Category": "-",
         "District": "HYDERABAD",
         "Filing Date": "12/02/2019",
         "Registration Date": "12/02/2019",
         "Listing Date": "21/06/2019",
         "Case Status": "PENDING"
         

,

"231": 
   

    "Advocate Name": "DAISY LEE",

    "No. of Cases": "28",

    "WP 1518/2019": 
         "Case Category": "NON-SERVICE",
         "District": "HYDERABAD",
         "Filing Date": "28/01/2019",
         "Registration Date": "28/01/2019",
         "Listing Date": "11/02/2019",
         "Case Status": "DISPOSEDClick here to see the Order"
          ,
       "WP 2896/2019": 
         "Case Category": "NON-SERVICE",
         "District": "HYDERABAD",
         "Filing Date": "12/02/2019",
         "Registration Date": "13/02/2019",
         "Listing Date": "-",
         "Case Status": "PENDING"
         
 


我正在考虑上述数据中的 2 个键 - "13638" 和 "231" 。我想访问“案例状态”字段并将其转换为数据框。

预期输出:


|病例状态|

待处理

待处理

DISPOSED点击这里查看订单

待处理

【问题讨论】:

【参考方案1】:

你可以通过遍历字典来得到它。

case_status_list = []
for key, value in data.items():
    for nested_key, nested_value in value.items():
        try:
            status = nested_value.get("Case Status", None)
            case_status_list.append(status)
        except AttributeError as e:
            pass
print(case_status_list)

输出:

['PENDING', 'PENDING', 'DISPOSEDClick here to see the Order', 'PENDING']

要转换成dataframe,可以refer this question

L = ['Thanks You', 'Its fine no problem', 'Are you sure']

#create new df 
df = pd.DataFrame('col':L)
print (df)

                   col
0           Thanks You
1  Its fine no problem
2         Are you sure

【讨论】:

如何在数据框或文本中收集所有值而不是打印出来? @NajmaNaaz 您可以将值附加到列表而不是打印它。我已经更新了答案

以上是关于如何在python中读取嵌套的json数据值?的主要内容,如果未能解决你的问题,请参考以下文章

c#如何读取json中的值

如何获取网页中的json数据?

使用 python/pandas 从特定文件夹中读取几个嵌套的 .json 文件到 excel 中

python读取json格式文件大量数据,以及python字典和列表嵌套用法详解

python读取json格式文件大量数据,以及python字典和列表嵌套用法详解

Objective C如何从嵌套的JSON中读取