Python字典到json不能理解的基础知识

2024-10-02 02:31:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个例子中,我可以用dict创建一个具有所需结构的JSON。你知道吗

import json

jsondata = {}
jsondata = {'type':'add', 'id':'','fields':{'message':'text', 'from':'email@email.com'}}
jsfields = jsondata, jsondata
print json.dumps(jsfields)

这是期望的输出。你知道吗

[
  {
    "id": "",
    "type": "add",
    "fields": {
      "from": "email@email.com",
      "message": "text"
    }
  },
  {
    "id": "",
    "type": "add",
    "fields": {
      "from": "email@email.com",
      "message": "text"
    }
  }
]

现在我不明白的是,如何将更多的json对象添加到这个数组中?你知道吗

从这一点上说,我不知道如何在jsfields中添加与下一个数组相同的内容。你知道吗

{
    "id": "",
    "type": "add",
    "fields": {
      "from": "email@email.com",
      "message": "text"
    }

}

Tags: textfromcomaddidjsonmessagefields
2条回答

jsfields = jsondata, jsondata

此行创建一个元组,其中包含jsondata的两个副本。元组有点像列表,但它是不可变的,这意味着在创建元组后不能向其中添加任何内容。你知道吗

您可能需要这样做来创建一个列表:

jsfields = [jsondata, jsondata]

这将创建一个包含jsondata的两个副本的列表。然后,您可以非常轻松地添加更多条目:

jsfields.append(some_other_dict)

您应该将JSON字符串转换回python对象,然后在列表中添加一个新项,然后再次将其转换为JSON。你知道吗

import json

jsondata = {}
jsondata = {'type':'add', 'id':'','fields':{'message':'text', 'from':'email@email.com'}}
jsfields = jsondata, jsondata
json_output = json.dumps(jsfields) # this is where your old output is
new_json = json.loads(json_output) # convert the old output back to python object
new_json.append(jsondata) # add new item to the list
print(json.dumps(new_json)) # convert to JSON again

相关问题 更多 >

    热门问题