gpt4 book ai didi

python - 在Python 3中递归遍历不规则的JSON层次结构以执行部分​​叶节点删除

转载 作者:行者123 更新时间:2023-12-01 06:37:21 24 4
gpt4 key购买 nike

所以,我有一个看起来像这样的 JSON block :

[
{
"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_type“007”的“子”叶节点并删除与该数据 block 关联的字段 1 条目。我在尝试隔离仅与正确类型的叶节点(子节点,而不是兄弟节点)关联的整个字典时遇到麻烦,以便我可以检查它的 x_type 是否正确并执行删除。

我不确定要从我拼凑在一起的递归函数传递或返回什么样的值。我以前从未在 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))
<小时/>
import json
print(json.dumps(new_data, indent=4))

输出:

[
{
"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": []
}
]
}
]
}
]
}
]

关于python - 在Python 3中递归遍历不规则的JSON层次结构以执行部分​​叶节点删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59607519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com