11

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

2
  • 1
    probably what you are looking for is simply assignment like data = { "agent": { "agentid", "john"} , "content": { "eventType": "view", "othervar": "new" } } Commented Sep 11, 2018 at 17:59
  • I would like to maintain the format I currently have of setting each key/value pair first. Is that possible? Cheers Commented Sep 11, 2018 at 18:05

1 Answer 1

29

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

Sign up to request clarification or add additional context in comments.

1 Comment

for pretty print: print(json.dumps(jsondata, indent=4))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.