Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

file

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() 
like image 746
Backo Avatar asked Apr 16 '14 13:04

Backo


1 Answers

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.

like image 160
Martijn Pieters Avatar answered Oct 08 '22 21:10

Martijn Pieters