Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I created nested JSON object with Python?

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

like image 264
Nicholas Avatar asked Sep 11 '18 17:09

Nicholas


People also ask

Can JSON objects be nested?

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.

How does Python handle nested JSON?

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.


1 Answers

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

like image 141
C. Fennell Avatar answered Oct 12 '22 15:10

C. Fennell