40

I am new to Python and I am playing with JSON data. I would like to retrieve the JSON data from a file and add to that data a JSON key-value "on the fly".

That is, my json_file contains JSON data as-like the following:

{"key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}

I would like to add the "ADDED_KEY": "ADDED_VALUE" key-value part to the above data so to use the following JSON in my script:

{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}

I am trying to write something as-like the following in order to accomplish the above:

import json

json_data = open(json_file)
json_decoded = json.load(json_data)

# What I have to make here?!

json_data.close()
martineau
  • 119,623
  • 25
  • 170
  • 301
Backo
  • 18,291
  • 27
  • 103
  • 170

3 Answers3

43

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Using this code I have a problem with adding new key-value. My file gets overwritten with a new key-value pair. – MrKarma4u Sep 18 '20 at 22:07
  • @MrKarma4u: the whole file is re-written, yes. The file is rewritten with the full dictionary, however, so if you are missing data it wasn't part of what was read from the file before adding the new key. – Martijn Pieters Sep 19 '20 at 10:55
12

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

import json

with open("your_json_file.txt", 'r') as f:
    data = json.loads(f.read()) #data becomes a dictionary

#do things with data here
data['ADDED_KEY'] = 'ADDED_VALUE'

#and then just write the data back on the file
with 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

0xff
  • 121
  • 2
9

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'))
bsoist
  • 775
  • 3
  • 10
  • How to check for the existence of ADDED_KEY? – Backo Apr 16 '14 at 15:23
  • My approach would depend on what I wanted to do if it did exist. How would you want to handle that if the key did already exist? – bsoist Apr 16 '14 at 15:25
  • I would like to overwrite the existing JSON value. However, for my curiosity, I am interested even to "raise" an error if the JSON key exists and to handle the case of "nesting". – Backo Apr 16 '14 at 16:21