I have the following code:
data = {}
data['agentid'] = 'john'
data['eventType'] = 'view'
json_data = json.dumps(data)
print json_date = {"eventType":"view,"agentid":"john"}
I would like to create a nested JSON object- for example::
{
"agent": { "agentid", "john"} ,
"content": {
"eventType": "view",
"othervar": "new"
}
}
How would I do this? I am using Python 2.7.
Cheers Nick
Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.
Python has built in functions that easily imports JSON files as a Python dictionary or a Pandas dataframe. Use pd. read_json() to load simple JSONs and pd. json_normalize() to load nested JSONs.
You could nest the dictionaries as follows:
jsondata = {}
agent={}
content={}
agent['agentid'] = 'john'
content['eventType'] = 'view'
content['othervar'] = "new"
jsondata['agent'] = agent
jsondata['content'] = content
print(json.dumps(jsondata))
Output:
print {"content": {"eventType": "view", "othervar": "new"}, "agent": {"agentid": "john"}}
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