pythonjsonfile-io

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:

{
    'name':'myname'
}

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 = f.read()
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.


Solution

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

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