如何从多层嵌套JSON文件中提取nodes_visited下的conditions字段值
问题解决步骤
错误原因
- 键路径错误:
nodes_visited是debug字典的子键,而非output的直接子键,直接调用output['nodes_visited']必然触发KeyError - 类型操作错误:
nodes_visited的值为列表类型,列表内的每个元素才是包含conditions字段的字典,无法直接对列表执行['conditions']取值操作
实现代码
你需要先按正确路径取值,再遍历列表提取conditions,最后通过正则匹配拿到@property-action:后对应的目标值,完整实现如下:
import pprint import re # 你的原有代码 debug = output['debug'] pp = pprint.PrettyPrinter(indent=4) pp.pprint(debug) # 1. 安全提取nodes_visited列表,键不存在时默认返回空列表避免报错 nodes_visited = debug.get('nodes_visited', []) extracted_values = [] # 2. 定义正则规则,匹配@property-action:后的非空格连续字符 action_pattern = re.compile(r'@property-action:(\w+)') for node in nodes_visited: # 3. 安全提取当前节点的conditions字段,不存在时默认返回空字符串 cond_content = node.get('conditions', '') # 4. 匹配所有符合规则的值,支持单条conditions下多个action的提取 matched_actions = action_pattern.findall(cond_content) if matched_actions: extracted_values.extend(matched_actions) # 输出最终结果,示例输出为 ['move', 'offer', 'loan', 'sell'] print(extracted_values)
补充说明
全程使用dict.get()方法取值,避免键不存在时直接抛出异常,提升代码健壮性。如果需要对提取结果去重且保留出现顺序,可在最后添加一行:
extracted_values = list(dict.fromkeys(extracted_values))
内容的提问来源于stack exchange,提问作者Brandon Jacobson
相关产品推荐
相关产品推荐

