You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归查找嵌套JSON同值元素路径时结果不符合预期问题

问题原因

你现有代码的问题是只要找到第一个匹配的目标值就会立刻终止遍历返回结果,不会继续查找后面的节点,所以重复查询相同src值时,每次返回的都是第一个匹配项的路径。

修复后的完整代码
import json

def breadcrumb_finder(json_node, target, current_path=None):
    # 初始化路径记录
    if current_path is None:
        current_path = []
    match_results = []
    # 当前节点匹配目标值,记录路径
    if json_node == target:
        match_results.append(current_path + [json_node])
        return match_results
    # 遍历字典类型节点
    if isinstance(json_node, dict):
        for key, value in json_node.items():
            child_matches = breadcrumb_finder(value, target, current_path + [key])
            match_results.extend(child_matches)
    # 遍历列表类型节点
    elif isinstance(json_node, list):
        for index, item in enumerate(json_node):
            child_matches = breadcrumb_finder(item, target, current_path + [str(index)])
            match_results.extend(child_matches)
    return match_results

# 加载JSON数据
data_str = r'''{"imagepanel":{"image":[{"scaled_image":{"classes":"w-full","aspect_ratios":"frame sm:4:3 xmed:4:3","art_directions":[{"alt":"River waves","src":"path/to/file/53339c03d67e6ee5-lesson-3.jpg","type":"jpg","media":"(min-width:900.1px)","sizes":"50vw","intrinsicwidth":"1411","intrinsicheight":"1000"},{"alt":"River waves","src":"path/to/file/53339c03d67e6ee5-lesson-3.jpg","type":"jpg","media":"(max-width:900px)","sizes":"100vw","intrinsicwidth":"0","intrinsicheight":"0"}]}}],"title":"<p><span class=\"drop-cap\" drop-cap=\"true\">WHAT TO WATCH</span></p>","cta_label":"SEE THE LIST","left_image":true}}'''
data = json.loads(data_str)

# 查找所有匹配的路径
target_src = "path/to/file/53339c03d67e6ee5-lesson-3.jpg"
all_nested_paths = breadcrumb_finder(data, target_src)

# 输出结果
for path in all_nested_paths:
    print(path)
输出结果
['imagepanel', 'image', '0', 'scaled_image', 'art_directions', '0', 'src', 'path/to/file/53339c03d67e6ee5-lesson-3.jpg']
['imagepanel', 'image', '0', 'scaled_image', 'art_directions', '1', 'src', 'path/to/file/53339c03d67e6ee5-lesson-3.jpg']

内容的提问来源于stack exchange,提问作者A l w a y s S u n n y

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:36:03