Home > Net >  trying to access nested dictionary keys in python
trying to access nested dictionary keys in python

Time:09-22

I need to load a json and read the content to edit it later. I am getting

{TypeError}string indices must be integers

here is the json structure (note-below is the format when json file is already loaded, else it shows double quotes)

data ={'a':'hello','b':'{"date1":"9/21/2021","date2":"9/22/2021"}','c':'new'}

when trying to access data['b']['date1'] it throws error

code is as follows

jsonfile=open(file.json, "r")
data = json.load(jsonfile)
jsonfile.close()
date = data['b']['date1']

CodePudding user response:

The content of data['b'] is a string which contains a JSON document:

'{"date1":"9/21/2021","date2":"9/22/2021"}'

Thus you should convert it first to JSON (dict / list):

data_b = json.loads(data['b'])

Now that it is converted to a dict, you can already access its keys:

data_b["date1"]

If you want to update those values, then update the dict and then convert it back to string and reassign to the original data:

import json

data = {'a':'hello','b':'{"date1":"9/21/2021","date2":"9/22/2021"}','c':'new'}

data_b = json.loads(data['b'])
data_b["date1"] = "updated 1"
data_b["date2"] = "updated 2"

data['b'] = json.dumps(data_b)
print(data)

Output:

{'a': 'hello', 'b': '{"date1": "updated 1", "date2": "updated 2"}', 'c': 'new'}

To write it back, you have to open the file in write-mode w and then use either json.dump() or file.write().

with open("file.json", 'w') as json_file:
    # Option 1
    json.dump(data, json_file)
    # Option 2
    # json_file.write(json.dumps(data))
  • Related