3

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"}
0

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This works fine! Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.