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

求助:Python提取JSON文件中所有component_name的代码问题排查

问题排查与修正

原代码的核心问题

  • 字段名错误:JSON中不存在child字段,存储子元素的字段是items,原代码调用desktop[x]['child']会直接触发KeyError。
  • 遍历范围不全:仅处理了desktop下的内容,完全遗漏了mobile中的component_name。
  • 节点处理遗漏:部分节点(如contact页面desktop里的row)自身就带有component_name,原代码未处理这类情况。
  • 遍历方式冗余:用range(len(desktop))遍历列表的写法不够简洁,直接遍历元素更直观。

修正后的代码

使用递归函数遍历所有层级的节点,确保不遗漏任何component_name:

import json

def find_component_names(node):
    # 检查当前节点是否有component_name,有则打印
    if 'component_name' in node:
        print(node['component_name'])
    # 遍历items中的子节点,递归处理
    if 'items' in node and isinstance(node['items'], list):
        for item in node['items']:
            find_component_names(item)

# 读取并解析JSON文件
with open("config-2_new.json", 'r') as f:
    obj = json.load(f)

# 遍历layout下的所有容器
for container in obj['layout'].values():
    # 处理pages下的所有页面
    if 'pages' in container:
        for page in container['pages'].values():
            # 处理desktop节点
            if 'desktop' in page:
                for node in page['desktop']:
                    find_component_names(node)
            # 处理mobile节点
            if 'mobile' in page:
                for node in page['mobile']:
                    find_component_names(node)
    # 处理容器直接挂载的mobile节点(匹配你提供的JSON结构)
    if 'mobile' in container:
        for node in container['mobile']:
            find_component_names(node)

代码说明

  1. 递归函数find_component_names会逐层检查节点,遇到component_name就打印,同时递归处理items中的所有子元素,适配嵌套结构。
  2. 遍历layout下的所有容器(如user、contact),覆盖所有可能存在component_name的desktop和mobile节点。
  3. 使用with语句管理文件,自动完成文件关闭操作,更安全规范。

内容的提问来源于stack exchange,提问作者Pooja Patil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:25:59