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.
First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want. Lastly, you would convert that JavaScript Object back into a JSON string.
Updating a JSON object in Python is as simple as using the built-in update() function from the json package we have imported. The update method is used to add a new key-value pair to the JSON string that we declared in our code.
It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With