我想像这样在 python 中创建 JSON 对象:
{
"to":["admin"],
"content":{
"message":"everything",
"command":0,
"date":["tag1",...,"tagn"]
},
"time":"YYYYMMDDhhmmss"
}
这是我在 python 中的代码:
import json
cont = [{"message":"everything","command":0,"data":["tag1","tag2"]}]
json_content = json.dumps(cont,sort_keys=False,indent=2)
print json_content
data = [{"to":("admin"),"content":json_content, "time":"YYYYMMDDhhmmss"}]
json_obj = json.dumps(data,sort_keys=False, indent =2)
print json_obj
但我得到的结果是这样的:
[
{
"content": "[\n {\n \"data\": [\n \"tag1\", \n \"tag2\"\n ], \n \"message\": \"everything\", \n \"command\": 0\n }\n]",
"to": "admin",
"time": "YYYYMMDDhhmmss"
}
]
有人可以帮帮我吗?谢谢
最佳答案
嵌套json
内容
json_content
是第一次调用 json.dumps()
返回的 json
字符串表示,这就是为什么你得到一个字符串版本第二次调用 json.dumps()
时的内容。在将原始内容 cont
直接放入 data
之后,您需要对整个 python 对象调用一次 json.dumps()
。
import json
cont = [{
"message": "everything",
"command": 0,
"data" : ["tag1", "tag2"]
}]
data = [{
"to" : ("admin"),
"content" : cont,
"time" : "YYYYMMDDhhmmss"
}]
json_obj = json.dumps(data,sort_keys=False, indent =2)
print json_obj
[
{
"content": [
{
"data": [
"tag1",
"tag2"
],
"message": "everything",
"command": 0
}
],
"to": "admin",
"time": "YYYYMMDDhhmmss"
}
]
关于python - 在 python 中制作 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38626933/