通过向子对象添加数据来更新“主”JSON对象 [英] Updating a 'master' JSON object by adding data to a subobject

查看:142
本文介绍了通过向子对象添加数据来更新“主”JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Lets say I have a list of JSON objects:

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}}]}]

我想迭代这个列表并拥有一个'Master'json对象:

I want to iterate through this list and have a single 'Master' json object:

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

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

The problem here is that I don't want to just 'update' the masterJson object with every new iteration. Essentially, the subobjects "Name" and "Date" will always be the same. What I want to do is add to the "features" subobject list only so that in the masterJson object it looks like this:

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}}]}

我目前的想法是拥有如下内容,但我无法让它为我工作。我如何实现这一目标?

My current idea is to have something like the following, but I can't get it to quite work for me. How do I achieve this?

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

推荐答案

此循环位在 masterJson dict中添加功能部分。

This loop bit adds the features part in the 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

在使用此部件之前,添加名称日期部分到 masterJson dict,您将拥有所需的结构。
tempList 是一个临时列表,用于保存不同的功能 dict。
干杯。

before using this part, add the Name and Date part to the masterJson dict and you will have the structure you require. tempList is a temporary list to hold the different features dict. cheers.

这篇关于通过向子对象添加数据来更新“主”JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆