

发布于 2025-07-22 17:57467浏览首先要理解一下什么是递归
递归指的是函数(或方法)直接或间接调用自身,适合问题可自然分解的场景
重点:必须要有终止条件,不然电脑容易罢工

def factorial(n):
if n == 0: # 基本情况:0! = 1
return 1
else:
return n * factorial(n-1) # 递归步骤:n! = n × (n-1)!影刀示例:递归读取指定JSON中的所有指定子KEY
首先捋一下基础逻辑:json需要解析成dict字典
字典包含键名和键值,键值包含列表、字典、字符串、数字等
根据用户指定需查询的dict ,来遍历每一个键值对
如果是列表则进一步深入,直到遍历项不包含列表和字典为止返回
递归流程
传参

运行结果
InvokeProcessResult_Dynamic_process8(result=[
[
1, '0->id'
],
[
101, '0->details->0->id'
],
[
102, '0->details->1->id'
],
[
2, '1->id'
],
[
201, '1->details->0->id'
],
[
2011, '1->details->0->sub_details->0->id'
],
[
2012, '1->details->0->sub_details->1->id'
],
[
202, '1->details->1->id'
]
], data=[
{'id': 1, 'name': '基础信息组', 'details': [
{'id': 101, 'type': '文本', 'content': '这是第一层嵌套的文本信息'
},
{'id': 102, 'type': '数字', 'content': 2025
}
]
},
{'id': 2, 'name': '扩展信息组', 'details': [
{'id': 201, 'type': '复合数据', 'sub_details': [
{'id': 2011, 'type': '日期', 'content': '2025-07-22'
},
{'id': 2012, 'type': '布尔值', 'content': True
}
]
},
{'id': 202, 'type': '文本', 'content': '这是与第一层嵌套同键名的文本信息'
}
]
}
], find_key='id', path=[])注意参数传递问题,能用循环搞定的尽量别用递归,此文章做纪录和参考使用。