Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add an element to json object using Python [duplicate]

I have a json string imported from a URL request. I need to insert an element to the existing object using python.

Here is my json file:

{"status_code": 200, "data": {"key1": value, "key2": value, "key3": -5, "key4": "key5", "key6": [{"key7": value, "key8": value}]}, "key9": "value"}

I need it to be like this:

{"status_code": 200, "data": {"key1": value, "key2": value, "key3": -5, "key4": "key5", "key6": [{"key7": value, "key8": value}]}, "key9": "value", "new_key": "new_value"}
like image 681
J.Doe Avatar asked Dec 07 '25 11:12

J.Doe


1 Answers

If you are on Python 3.6+ you can do the following. Note that the JSON values are strings rather than the dicts you posted.

import json

old = '{"status_code": 200, "data": {"key1": "value", "key2": "value", "key3": -5, "key4": "key5", "key6": [{"key7": 1542603600, "key8": 94}]}, "key9": "OK"}'

new = json.dumps({**json.loads(old), **{"new_key": "new_value"}})

>>> new
'{"status_code": 200, "data": {"key1": "value", "key2": "value", "key3": -5, "key4": "key5", "key6": [{"key7": 1542603600, "key8": 94}]}, "key9": "OK", "new_key": "new_value"}'

If pre 3.6 you need to store the dict someplace to update

temp = json.loads(old)
temp.update({"new_key": "new_value"})
new = json.dumps(temp)
like image 56
bphi Avatar answered Dec 10 '25 01:12

bphi