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

遍历ruletree JSON提取特定键值:修复TypeError并实现预期输出

修复遍历JSON时的TypeError并实现需求

错误原因

  • ruletree['rules']['children']是列表类型,直接用['behaviors']字符串索引访问,违反了列表只能用整数/切片索引的规则,触发TypeError。
  • 代码中未定义N/A,需用字符串'N/A'替代。
  • 错误引用未定义的options变量,未逐层访问嵌套的JSON结构。

修复后的代码

ruletree = {
    "account": "act_F-AC-1234",
    "contract": "ctr_F-1234",
    "propertyName": "www.domain.com",
    "rules": {
        "name": "default",
        "children": [
            {
                "name": "Route One",
                "children": [],
                "behaviors": [
                    {
                        "name": "origin",
                        "options": {
                            "originType": "CUSTOMER",
                            "hostname": "first.gateway.com",
                        },
                    }
                ],
            },
            {
                "name": "Route Two",
                "children": [],
                "behaviors": [
                    {
                        "name": "origin",
                        "options": {
                            "originType": "CUSTOMER",
                            "hostname": "second.gateway.com",
                        },
                    }
                ],
            },
        ],
    },
}

# 收集所有hostname
hostnames = []
# 遍历每个子路由
for route in ruletree['rules']['children']:
    # 遍历路由下的每个behavior
    for behavior in route['behaviors']:
        # 取出hostname,不存在则用'N/A'替代
        hostname = behavior['options'].get('hostname', 'N/A')
        hostnames.append(hostname)

# 构造期望的输出结构
result = {
    "propertyName": ruletree['propertyName'],
    "hostnames": ", ".join(hostnames)
}

print(result)

输出结果

{"propertyName": "www.domain.com", "hostnames": "first.gateway.com, second.gateway.com"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:28:12