【问题标题】:Python dictionary to json cannot understand the basicsPython字典到json无法理解基础知识
【发布时间】:2018-06-29 14:22:43
【问题描述】:

在这个例子中,我可以从一个具有所需结构的字典中创建一个 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"
    }

}

【问题讨论】:

  • 我不好意思回答我自己的问题。但我只需要将 dict 附加到列表中。
  • 这发生在我们最好的人身上:P

标签: python arrays json dictionary


【解决方案1】:

jsfields = jsondata, jsondata

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

您可能希望这样做来创建一个列表:

jsfields = [jsondata, jsondata]

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

jsfields.append(some_other_dict)

【讨论】:

    【解决方案2】:

    您应该将 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 2015-11-20
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多