How to dynamically build a JSON object with Python?
How to dynamically build a JSON object with Python?
Question by Backo
I am new to Python and I am playing with JSON data. I would like to dynamically build a JSON object by adding some key-value to an existing JSON object.
I tried the following but I get TypeError: 'str' object does not support item assignment
:
import json
json_data = json.dumps({})
json_data["key"] = "value"
print 'JSON: ', json_data
Answer by Martijn Pieters♦
You build the object before encoding it to a JSON string:
import json
data = {}
data['key'] = 'value'
json_data = json.dumps(data)
JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.
Answer by Milovan Tomašević
json.loads
take a string as input and returns a dictionary as output.json.dumps
take a dictionary as input and returns a string as output.
If you need to convert JSON data into a python object, it can do so with Python3
, in one line without additional installations, using SimpleNamespace
and object_hook
:
from string
import json
from types import SimpleNamespace
string = '{"foo":3, "bar":{"x":1, "y":2}}'
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))
print(x.foo)
print(x.bar.x)
print(x.bar.y)
output:
3
1
2
from file:
JSON object: data.json
{
"foo": 3,
"bar": {
"x": 1,
"y": 2
}
}
import json
from types import SimpleNamespace
with open("data.json") as fh:
string = fh.read()
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))
print(x.foo)
print(x.bar.x)
print(x.bar.y)
output:
3
1
2
from requests
import json
from types import SimpleNamespace
import requests
r = requests.get('https://api.github.com/users/MilovanTomasevic')
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(r.text, object_hook=lambda d: SimpleNamespace(**d))
print(x.name)
print(x.company)
print(x.blog)
output:
Milovan Tomašević
NLB
milovantomasevic.com
For more beautiful and faster access to JSON response from API, take a look at this response.
Share on: