How to add a key-value to JSON data retrieved from a file? How to add a key-value to JSON data retrieved from a file? json json

How to add a key-value to JSON data retrieved from a file?


Your json_decoded object is a Python dictionary; you can simply add your key to that, then re-encode and rewrite the file:

import jsonwith open(json_file) as json_file:    json_decoded = json.load(json_file)json_decoded['ADDED_KEY'] = 'ADDED_VALUE'with open(json_file, 'w') as json_file:    json.dump(json_decoded, json_file)

I used the open file objects as context managers here (with the with statement) so Python automatically closes the file when done.


Json returned from json.loads() behave just like native python lists/dictionaries:

import jsonwith open("your_json_file.txt", 'r') as f:    data = json.loads(f.read()) #data becomes a dictionary#do things with data heredata['ADDED_KEY'] = 'ADDED_VALUE'#and then just write the data back on the filewith open("your_json_file.txt", 'w') as f:    f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))#I added some options for pretty printing, play around with them!

For more info check out the official doc


You can do

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

OR

json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})

which works nicely if you want to add more than one key/value pair.

Of course, you may want to check for the existence of ADDED_KEY first - depends on your needs.

AND I assume you want might want to save that data back to the file

json.dump(json_decoded, open(json_file,'w'))