本文介绍了如何使用Python创建嵌套的JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

data = {}
data['agentid'] = 'john'
data['eventType'] = 'view'
json_data = json.dumps(data)

print json_date = {"eventType":"view," agentid:" john}

print json_date = {"eventType":"view,"agentid":"john"}

我想创建一个嵌套的JSON对象-例如:

I would like to create a nested JSON object- for example::

{
    "agent": { "agentid", "john"} ,
    "content": {
        "eventType": "view",
        "othervar": "new"
    }
}

我该怎么做?我正在使用Python 2.7.

How would I do this? I am using Python 2.7.

欢呼尼克

推荐答案

您可以按以下方式嵌套字典:

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))

输出:

这篇关于如何使用Python创建嵌套的JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:15