删除嵌套 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 中对我来说最好的方法是什么?
如果您使用有效的 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)
有很多种方法。
我有一个 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 中对我来说最好的方法是什么?
如果您使用有效的 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)
有很多种方法。