python - 在 python 中制作 JSON 对象

标签 python json

我想像这样在 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/

相关文章:

javascript - 用 Angular 显示json结果

Python::NLTK 连接句子列表

python - 使用 gspread 访问谷歌文档

Python:添加到for循环中和外部的列表列表

javascript - 在Karate框架中的RunnerTest.have中编写javascript公共(public)函数

javascript - 我获取 JSON 对象中的记录数的代码不起作用?

python - 使用 networkx 加权边缘列表时出错

python - 脚本终止时释放 Python Flask 端口

python - 将抓取的 json 文件读取到 python 中

javascript - 如何将 JSON 对象写入现有 JSON 文件