【问题标题】:Key Error while Parsing Json file using Python使用 Python 解析 Json 文件时出现键错误
【发布时间】:2019-06-20 11:32:56
【问题描述】:

我们将 Source 作为 Json 文件,我们正在尝试解析数据并创建输出 CSV 文件

在某些情况下,我们不会收到 Json 文件中的某些属性。

当我尝试使用以下代码获取长度及其值时,我收到“密钥错误”。下面是我的代码。

for j in range(len(json_file['entity'][i]['data']['attrb']['DEPT']['group'])):
    for key in json_file['entity'][i]['data']['attrb']['DEPT']['group'][j].keys():
        try:
            temp[key] = json_file['entity'][i]['data']['attrb']['DEPT']['group'][j][key]['values'][0]['value']
        except:
            temp[key] = None

['entity'][i]['data']['attrb'] 将始终可用,但'DEPT' 对于某些json 文件我可能没有它。

错误:

“关键错误:找不到‘DEPT’”。

我该如何克服这个问题,请帮助我提出任何建议..

请在下面找到示例数据..

{
  "entity": [
    {
  "data": {
    "attrb": {

      "DEPT": {
        "group": [
          {
            "DEPTID": {
              "values": [
                {
                  "value": "D12345"
                }
              ]
            },
            "DEPTNO": {
              "values": [
                {
                  "value": "302222201"
                }
              ]
            }
          }
        ]
      }
    }
   }
  }
 ]

 }

【问题讨论】:

  • 为了帮助您,我们还需要查看 JSON 数据。
  • 顺便说一句,您正在以一种非常非 Pythonic 的方式迭代该 ['group'] 字典。查看.items() 而不是range().keys()
  • @AKX ... 非常感谢您的回复。我将在几分钟内添加示例文件。
  • 使用dict.get()方法代替[],即json_file.get('entity', [])代替json_file['entity']
  • 用于带有不确定键的字典。使用 dict.get(key, default) 代替。如果键不存在,它将返回默认值

标签: python json pandas


【解决方案1】:

让我们一步一步地分解它。

你的字符串是

import json   

json_string = '''{
  "entity": [
    {
  "data": {
    "attrb": {
      "DEPT": {
        "group": [
          {
            "DEPTID": {
              "values": [
                {
                  "value": "D12345"
                }
              ]
            },
            "DEPTNO": {
              "values": [
                {
                  "value": "302222201"
                }
              ]
            }
          }
        ]
      }
    }
   }
  }
 ]
 }'''

以及生成的 json 字典:

test = json.loads(json_string)

首先,返回所有属性(你提到的 'attrib' 被认为是一个有效的键)。

attribs = [test['entity'][i]['data']['attrb'] for i in range(len(test['entity']))]

现在属性输出为

>>> attribs
[{'DEPT': {'group': [{'DEPTID': {'values': [{'value': 'D12345'}]},
 'DEPTNO': {'values': [{'value': '302222201'}]}}]}}]

随后,正如您所提到的,“DEPT”可能是也可能不是有效的密钥。从此我们使用 de dict.get 方法:

dept = attribs[0].get('DEPT')
>>> dept
{'group': [{'DEPTID': {'values': [{'value': 'D12345'}]},
'DEPTNO': {'values': [{'value': '302222201'}]}}]}

但是,如果 'DEPT' 不是有效的密钥,那么 get('DEPT') 将返回 None:

_dict= {}
>>> print(_dict.get('DEPT'))
None

或者,如果您希望返回 None 以外的其他默认值,那么您会

_dict.get('DEPT', your_default_value)

其中 your_default_value 是任意变量。

希望这会有所帮助。

【讨论】:

  • 非常感谢您的回复。我可以和你分享我的完整代码吗?
  • 当然。但是我的回答解决了你的问题吗?
  • 未完全解决,想知道我错过了哪里。我可以把代码邮寄给你还是我需要把它粘贴在这里?
  • 粘贴到超链接中。
  • 我以超链接的形式添加了代码。这是我现有的代码。请看一下并帮助我提出一些建议..
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 2014-09-17
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
相关资源
最近更新 更多