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"}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With