vendredi 24 avril 2020

Read complex json file in python

Actual Json is:

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

My Code is

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

and the error is:

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',)

Reason: All the items in the title2 dict will not contain "tags". so, if there is no 'tags' or the tags['name'], then the abc_name = ''

i need the list of lists (titleID, abc_id, abc_name).

Expected output :

['1234','abc-0123','abc-name']
['1234','abc-4567','']

Aucun commentaire:

Enregistrer un commentaire