【问题标题】:Make JSON Object in python在python中制作JSON对象
【发布时间】:2016-12-02 06:56:06
【问题描述】:

我想像这样在 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"
  }
]

有人可以帮我吗?谢谢你

【问题讨论】:

标签: python jsonobject


【解决方案1】:

嵌套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"
  }
]

【讨论】:

  • 救我一命。非常感谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2023-02-16
  • 1970-01-01
  • 2017-02-23
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多