提问人:Sue_ka 提问时间:3/15/2021 最后编辑:Sue_ka 更新时间:3/16/2021 访问量:244
删除嵌套 JSON 对象中的元素并将其展平
Deleting elements in nested JSON object and flattening it
问:
我有一个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:字典在迭代期间更改了大小”。我在 Python 中做到这一点的最佳方法是什么?
答:
0赞
Sumit Jha
3/16/2021
#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)
有很多方法可以做到这一点。
评论
0赞
Sue_ka
3/16/2021
谢谢!我理解其中的逻辑,它使我不必明确定义字典的名称变得更加容易。
评论