递归遍历Python3中参差不齐的JSON层次结构以执行部分叶节点删除
我有一个JSON块,看起来有点像这样:递归遍历Python3中参差不齐的JSON层次结构以执行部分叶节点删除,python,json,python-3.x,dictionary,recursive-datastructures,Python,Json,Python 3.x,Dictionary,Recursive Datastructures,我有一个JSON块,看起来有点像这样: [ { "children": [ { "address": "123 Main Street", "class": "blarg", "children": [ { "children": [ {
[
{
"children": [
{
"address": "123 Main Street",
"class": "blarg",
"children": [
{
"children": [
{
"children": [
{
"y_type": "string",
"x_type": "002",
"002_id": 2222,
"updated_at": "2018-03-29T13:47:42.986Z",
"field020": "AAA",
"field030": "DDD"
},
{
"y_type": "bool",
"x_type": "007",
"007_id": 2222,
"updated_at": "2018-03-29T13:47:42.986Z",
"field1": True,
"field2": True
}
],
"create_at": "2018-03-29T13:45:20.875Z",
"x_id": "3e0e1b44-ac0d-4bf7-985e-11d74b8be323",
"junk_field": {},
"x_type": "000",
"timezone": "America/New_York",
"update_at": "2018-03-29T13:45:20.875Z"
},
{
"sibling": [1,2,3]
}
]
}
]
}
]
}]
我需要做的是找到x_类型为“007”的“子”叶节点,并删除与该数据块关联的字段1条目。我在尝试隔离与正确类型的叶节点(子节点,而不是同级节点)关联的整个dict时遇到了问题,因此我可以检查它是否为正确的x_类型并执行删除操作
我不确定从我拼凑的递归函数传递/返回什么类型的值。我以前从未在Python中进行过递归,更不用说针对粗糙的JSON层次结构了,所以我可以使用一些帮助/指导来了解使用/google的方法。如果你能帮我朝正确的方向走,我将不胜感激 您可以使用递归解包字典:
def d_filter(d):
return {**({a:b for a, b in d.items() if d.get('x_type') != '007' or a != 'field1'}), \
'children':list(map(d_filter, d.get('children', [])))}
new_data = list(map(d_filter, data))
输出:
[
{
"children": [
{
"address": "123 Main Street",
"class": "blarg",
"children": [
{
"children": [
{
"children": [
{
"y_type": "string",
"x_type": "002",
"002_id": 2222,
"updated_at": "2018-03-29T13:47:42.986Z",
"field020": "AAA",
"field030": "DDD",
"children": []
},
{
"y_type": "bool",
"x_type": "007",
"007_id": 2222,
"updated_at": "2018-03-29T13:47:42.986Z",
"field2": true,
"children": []
}
],
"create_at": "2018-03-29T13:45:20.875Z",
"x_id": "3e0e1b44-ac0d-4bf7-985e-11d74b8be323",
"junk_field": {},
"x_type": "000",
"timezone": "America/New_York",
"update_at": "2018-03-29T13:45:20.875Z"
},
{
"sibling": [
1,
2,
3
],
"children": []
}
]
}
]
}
]
}
]
这让我走上了正确的道路。TYVM!!我感谢你花时间回答这个问题!!你刚刚让我不用向老板解释为什么这么晚了…@Squish88很乐意帮忙!
[
{
"children": [
{
"address": "123 Main Street",
"class": "blarg",
"children": [
{
"children": [
{
"children": [
{
"y_type": "string",
"x_type": "002",
"002_id": 2222,
"updated_at": "2018-03-29T13:47:42.986Z",
"field020": "AAA",
"field030": "DDD",
"children": []
},
{
"y_type": "bool",
"x_type": "007",
"007_id": 2222,
"updated_at": "2018-03-29T13:47:42.986Z",
"field2": true,
"children": []
}
],
"create_at": "2018-03-29T13:45:20.875Z",
"x_id": "3e0e1b44-ac0d-4bf7-985e-11d74b8be323",
"junk_field": {},
"x_type": "000",
"timezone": "America/New_York",
"update_at": "2018-03-29T13:45:20.875Z"
},
{
"sibling": [
1,
2,
3
],
"children": []
}
]
}
]
}
]
}
]