【问题标题】:Read complex json file in python在python中读取复杂的json文件
【发布时间】:2020-04-24 21:29:50
【问题描述】:

实际的 Json 是:

{
  "title1": {
    "titleID": "1234",
    "titlename": "a-b-c",
  },
  "title2": [
    {
      "block": "0.0.0.0/26",
      "abc_id": "abc-0123",
      "tags": [{ "key": "Name", "value": "abc-name"},
               { "key": "env", "value": "dev"}]
    },
    {
      "block": "1.2.0.0/26",
      "abc_id": "abc-4567"
    },
    {
      "block": "0.0.0.0/26",
      "abc_id": "abc-8999",
      "tags": [{ "key": "Name", "value": "xyz-name"}]
    },
    {
      "block": "0.0.0.0/26",
      "abc_id": "abc-7766",
      "tags": [{ "app": "Name", "value": "web-app"}]
    }

  ]
}

我的代码是

with open('/tmp/temp.json') as access_json:
    read_content = json.load(access_json)
    for key1, value1 in read_content.items():
        if key1 == "title1":
            title_id = value1['titleID']
        if key1 == "title2":
            title2_access = read_content['title2']
            for title2_data in title2_access:
                for key2, value2 in title2_data.items():
                    if key2 == "abc_id":
                        abc_id = value2
                    if key2 == "tags":
                        tags_access = read_content['tags'] 
                        for tags_data in tags_access:
                            for key3, value3 in tags_data.items():
                                if key3 == "Name":
                                    abc_name = value3

错误是:

Traceback (most recent call last):
  File "/tmp/runscript.py", line 123, in <module>
    runpy.run_path(temp_file_path, run_name='__main__')
  File "/usr/local/lib/python3.6/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "/usr/local/lib/python3.6/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/usr/local/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmp/glue-python-scripts-lw031e0z/tsf_dev.py", line 160, in <module>
KeyError: 'tags'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/tmp/runscript.py", line 142, in <module>
    raise e_type(e_value).with_traceback(new_stack)
  File "/tmp/glue-python-scripts-lw031e0z/tsf_dev.py", line 160, in <module>
KeyError: KeyError('tags',)

原因:title2 字典中的所有项目都不包含“标签”。所以,如果没有 'tags' 或 tags['name'],那么 abc_name = ''

我需要列表列表 (titleID, abc_id, abc_name).

预期输出:

['1234','abc-0123','abc-name']
['1234','abc-4567','']
['1234','abc-8999','xyz-name']
['1234','abc-7766','']

有一个“title2”的字典, 它包含 abc_id 并且少数项目也包含“标签”。 如果没有标签,那么 abc-name 应该是 ''。 如果没有 Key:"name",那么 abc-name 应该是 ''。 如果字典中有标签和 key: "name",那么 abc-name 应该是 title2[tags][value: ""] 中存在的值,其中 title2[tags][key is "name"]

【问题讨论】:

  • 你认为的变量“read_content”是什么?
  • 你的预期输出是什么?
  • tags['name'],这是什么意思?代码中的任何地方都没有这样的键
  • 请将完整错误消息编辑到您的问题中。
  • 为什么不做一些简单的调试:在每个for 循环中添加一些打印语句,以便查看影响代码的变量值?异常之前的打印输出将帮助您找出问题所在。

标签: python json list for-loop if-statement


【解决方案1】:

您有太多 if 语句和 for 循环来正确处理您的代码。使用字典get 方法的默认选项来处理数据不存在的情况,如下所示。

title_id = read_content.get('title1', {}).get('titleID', '')

for block in read_content['title2']:
    id_ = block.get('abc_id', '')
    tags = block.get('tags', [{}])
    for tag in tags:
        if tag.get('key', '') == 'Name':
            name = tag.get('value', '')
        else:
            name = ''
        vals = [title_id, id_, name]
        print(vals)

['1234', 'abc-0123', 'abc-name']
['1234', 'abc-0123', '']
['1234', 'abc-4567', '']
['1234', 'abc-8999', 'xyz-name']
['1234', 'abc-7766', '']

【讨论】:

  • 嗨,谢谢你的代码,它很简单,但只有标签[key: "name"] 才应该作为 abc-name 值。你能看看这个问题。再次。你会明白的。
猜你喜欢
  • 2012-07-29
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2015-04-13
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多