簡體   English   中英

在python讀取復雜的json文件

[英]Read complex json file in python

實際 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)

預計 output:

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

有一個“title2”的字典,它包含 abc_id,少數項目也包含“tags”。 如果沒有標簽,那么 abc-name 應該是 ''。 如果沒有 Key: "name",那么 abc-name 應該是 ''。 如果字典中有標簽和鍵:"name",則 abc-name 應該是 title2[tags][value: ""] 中存在的值,其中 title2[tags][key is "name"]

你有太多的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', '']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM