How do I created nested JSON object with Python?

Viewed 30748

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

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

Related