Python read JSON file and modify

2019-01-07 11:14发布

问题:

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.

回答1:

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


回答2:

falsetru's solution is nice, but has a little bug:

Suppose original 'id' length was larger than 5 characters. When we then dump with the new 'id' (134 with only 3 characters) the length of the string being written from position 0 in file is shorter than the original length. Extra chars (such as '}') left in file from the original content.

I solved that by replacing the original file.

import json
import os

filename = 'data.json'
with open(filename, 'r') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.

os.remove(filename)
with open(filename, 'w') as f:
    json.dump(data, f, indent=4)