【问题标题】:Updating a 'master' JSON object by adding data to a subobject通过向子对象添加数据来更新“主”JSON 对象
【发布时间】:2019-01-30 01:19:44
【问题描述】:

假设我有一个 JSON 对象列表:

list = [{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 2, "Zone": "A"}, "geo": {"x": 10, "y": 20}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 3, "Zone": "D"}, "geo": {"x": 21, "y": 8}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 5, "Zone": "C"}, "geo": {"x": 15, "y": 10}}]}]

我想遍历这个列表并拥有一个“主”json 对象:

masterJson = {}
for item in list:
    print(item)

这里的问题是我不想在每次新迭代时都“更新”masterJson 对象。本质上,子对象“名称”和“日期”将始终相同。我想要做的只是添加到“功能”子对象列表中,以便在 masterJson 对象中看起来像这样:

masterJson = {"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 2, "Zone": "A"}, "geo": {"x": 10, "y": 20}}, {"attributes": {"OID": 3, "Zone": "D"}, "geo": {"x": 21, "y": 8}}, {"attributes": {"OID": 5, "Zone": "C"}, "geo": {"x": 15, "y": 10}}]}

我目前的想法是有类似以下的东西,但我无法让它完全适合我。我如何做到这一点?

list = [{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 2, "Zone": "A"}, "geo": {"x": 10, "y": 20}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 3, "Zone": "D"}, "geo": {"x": 21, "y": 8}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 5, "Zone": "C"}, "geo": {"x": 15, "y": 10}}]}]
masterJson = list[0]
for item in list:
    for item["features"]:
        masterJson["features"] = (item["features"])

print(masterJson)

另一种变化:

masterJson = list[0]
for item in list:
    for k in item:
        if k not in masterJson["features"]
            masterJson["features"] = (item["features"])

print(masterJson)

注意:结果好像是"features": "features"

【问题讨论】:

  • 我不知道,但可能是因为有人撤销了他/她的投票。

标签: python json python-3.x iteration updates


【解决方案1】:

此循环位在masterJson dict 中添加特征部分。

tempList = []
masterJson = {}
masterJson['Name'] = list[0]['Name']
masterJson['Date'] = list[0]['Date']
for item in list:
    tempList.extend(item['features'])
masterJson['features']=tempList

在使用这部分之前,将NameDate 部分添加到masterJson 字典中,您将拥有所需的结构。 tempList 是一个临时列表,用于保存不同的 features 字典。 干杯。

【讨论】:

  • 我有点困惑; tempList 是什么?我是否将它定义为只是一个空字典?另外,我正在制作 masterJson = list[0],所以它以NameDatefirst features 开头。所以,我只是扩展features?你是这个意思吗
  • 啊抱歉。我编辑了我的答案以包括tempListmasterJson 的初始化。不要将list[0] 添加到masterJson。而是将NameDate 部分分别添加到masterJson。我建议选择一次为 dict 项目编写所有内容,而不是选择稍后追加。它使您的代码更简单。
  • 完美运行!非常感谢! :-)
  • 在我看来,看看一些Data Structure Tutorial。这可能有助于学习。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 2013-09-23
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 2018-10-18
相关资源
最近更新 更多