codeBarer codeBarer - 3 months ago 70
JSON Question

Python read JSON file and modify

Hi I am trying to take the data from a json file and insert and id then perform POST REST.
my file data.json has:


and I would like to add an id so that the json data looks like:

'id': 134,
'name': 'myname'

So I tried:

import json
f = open("data.json","r")
data =
jsonObj = json.loads(data)

I can't get to load the json format file.
What should I do so that I can convert the json file into json object and add another id value.


Set item using data['id'] = ....

import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)