从JSON结构提取多组键值对报错:TypeError问题求助
问题解决:从JSON提取指定字段并生成新结构
原始JSON结构
{ 'propertyName': 'www.property1.com', 'propertyVersion': 1, 'etag': 'jbcas6764023nklf78354', 'rules': { 'name': 'default', 'children': [{ 'name': 'Route', 'children': [], 'behaviors': [{ 'name': 'origin', 'options': { 'originType': 'CUSTOMER', 'hostname': 'www.origin1.com' } }] }] } }
需求说明
提取propertyName和所有hostname的值,生成如下格式的新JSON:
{ "properties": [ { "propertyName": "www.property1.com", "hostnames": ["www.origin1.com", "www.origin2.com"] }, { "propertyName": "www.property1.com", "hostnames": ["www.origin1.com", "www.origin2.com"] } ] }
错误代码及问题
用户原代码:
hostnames = result.json() hostnameslist = [host['hostname'] for host in hostnames['rules']['children']['behaviors']['options']] print(hostnameslist)
运行报错:TypeError: list indices must be integers or slices, not str
错误原因
hostnames['rules']['children']是列表类型,不能直接用字符串键取值,必须先通过索引(比如[0])获取列表内的字典元素。behaviors同样是列表结构,需要先定位到具体元素,才能访问其下的options属性。
修正后的代码
import json # 解析返回的JSON数据 hostnames = result.json() # 提取顶层的propertyName property_name = hostnames['propertyName'] # 遍历嵌套结构,收集所有hostname hostnames_list = [] # 遍历children列表中的每个子规则 for child in hostnames['rules']['children']: # 遍历当前子规则下的所有behavior for behavior in child['behaviors']: # 仅提取origin类型的hostname(按需选择,可去掉判断) if behavior['name'] == 'origin': hostname = behavior['options']['hostname'] hostnames_list.append(hostname) # 构造目标JSON结构 output = { 'properties': [ { 'propertyName': property_name, 'hostnames': hostnames_list }, # 如需多个条目,可重复或根据实际逻辑生成 { 'propertyName': property_name, 'hostnames': hostnames_list } ] } # 打印结果或保存到文件 print(json.dumps(output, indent=4)) # 保存到文件的执行代码 # with open('output.json', 'w') as f: # json.dump(output, f, indent=4)
代码说明
- 逐层处理嵌套列表:先遍历
children列表,再遍历每个子项的behaviors列表,确保正确访问字典属性。 - 增加类型判断(
behavior['name'] == 'origin'),避免提取非origin类型的无关hostname,可根据实际需求移除。 - 按需求构造目标结构,支持直接打印结果或保存为JSON文件。
内容的提问来源于stack exchange,提问作者francorocks
相关产品推荐
相关产品推荐

