【问题标题】:Deleting elements in nested JSON object and flattening it删除嵌套 JSON 对象中的元素并将其展平
【发布时间】:2021-03-15 15:57:38
【问题描述】:

我有一个 JSON 对象,如下所示。

[
    {
    "metadata": {
        "Name": "Mike",
        "Age": 28,
        "DOB": "05/19/1992",
        "Profile" : {
            "type" : "standard",
            "payment" : "credit_card"
            },
        "Id" : "xxxyyxx"
        },
     "other" : False,
     "statistics": {
        "clicks": 32,
        "comments": "some text here"
        }
    },
    {
    "metadata": {
        "Name": "Andy",
        "Age": 24,
        "DOB": "10/01/1989",
        "Profile" : {
            "type" : "standard",
            "payment" : "credit_card"
            },
        "Id" : "xxyyyxx"
        },
     "other" : False,
     "statistics": {
        "clicks": 17,
        "comments": "some text here"
        }
    },    ​
]

我想删除此 JSON 对象中的元素,以便将其展平,如下所示,同时删除不必要的项目。我希望它如下所示。

[
    {
    "Id" = "xxxyyxx"
    "clicks": 32
    "comments": "some text here"
    },
    {
    "Id" = "xxyyyxx"
    "clicks": 17
    "comments": "some text here"
    }
]

我尝试尝试使用 pop 删除对象,但我收到“RuntimeError: dictionary changed size during iteration”。对我来说,在 Python 中进行此操作的最佳方式是什么?

【问题讨论】:

标签: python json python-2.7 nested-lists


【解决方案1】:

如果使用有效的 json,则可以递归搜索每个对象,如下所示:

data = [] # input object
def id_generator(dict_var, attributes):
    for k, v in dict_var.items():
        if k in attributes:
            yield k, v
        elif isinstance(v, dict):
            for id_val in id_generator(v, attributes):
                yield id_val
results = []
search = ("clicks", "Id", "comments")
for row in data: 
    result = {}
    for k, v in id_generator(row, search):
        result[k] = v
    results.append(result)
    
print(results)

有很多方法可以做到。

【讨论】:

  • 谢谢!我理解这个逻辑,它使我不必明确定义字典的名称变得更容易。
猜你喜欢
  • 1970-01-01
  • 2021-10-19
  • 2012-05-29
  • 2019-01-17
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
相关资源
最近更新 更多