遍历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
相关产品推荐
相关产品推荐

