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 json

with 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.

Leave a Comment