Reputation: 10697
How can I append a line to a json
file and overwrite it with the same name?
data.json
{
'a': 1,
'b': 2}
I tried
with open('data.json', 'r+') as json_file:
data = json.load(json_file)
data.update({'c': 3})
json.dump(data,json_file)
but this appends all the data, not just the intended line
Upvotes: 0
Views: 131
Reputation: 1942
First you need to read the JSON file and pass a second argument in the json.load()
method, that being to preserve the order of the dictionary. So when assigning a key-value pair to the dictionary, OrderedDict will automatically append it to the end. Finally, write to the file.
import json
from collections import OrderedDict
with open('data.json', 'r') as json_file:
data = json.load(json_file, object_pairs_hook=OrderedDict)
data['c'] = 3
with open('data.json', 'w') as json_file:
json.dump(data, json_file)
Upvotes: 2