0

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']
5
  • 2
    this is not a nested dictionary. Commented Sep 21, 2021 at 16:55
  • 1
    Because 'b'’s key is a string, not a dict. You can use the ast.literal_eval function or json library to convert the string into a dict. Commented Sep 21, 2021 at 16:55
  • What is unclear about the message? Commented Sep 21, 2021 at 16:55
  • I want to read date1 and date2 and need to update those in the json file but while trying to access date1, I get the mentioned error. How can I access those keys that are inside b ? Commented Sep 21, 2021 at 16:58
  • can anyone tell if its not a nested dictionary then what kind of structure it is ? Commented Sep 21, 2021 at 18:25

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

7 Comments

thanks for the details Niel. I still have a little confusion when writing it back to the file: jsonfile=open(file.json, "r") data = json.load(jsonfile) date_1 = json.loads(data['b']) jsonfile.close() data_1["date1"] = "updated 1" data_1["date2"] = "updated 2" jsonfile = open("file.json", "w+") jsonfile.write(json.dumps(data_1)) jsonfile.close() how to handle that in file, its replacing the file with only b's content
@viki It is because you are only dumping data_1 which only contains the contents for b. What you need is the whole data. I updated my answer to include how the updated json must be updated. Could you check if it works on your side?
I tried data and data_1 while dumping. The json file doesn't get any update when using data, but it gets updated and provide me only b value when using data_1. Not sure why. I have provide the code on the above comment, not sure how to format it like you are doing for proper reading
the update that we are making on data_1 is not getting into data. So the json file stays the same. not sure how to handle it
I found my mistake, I was missing one step data['b'] = json.dumps(data_b). I think I got this working with you help. Thanks a lot. Appreciate timely help
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.