Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 534
codeBarer Avatar asked Jan 10 '14 03:01

codeBarer


People also ask

How do I change the value of a JSON file?

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.

How do you update a JSON object in Python?

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.

How do I read a JSON file in Python?

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.


1 Answers

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 
like image 55
falsetru Avatar answered Sep 28 '22 09:09

falsetru