如何提取嵌套列表内字典的hostname值?解决TypeError问题
问题:提取嵌套JSON中的Hostname时触发TypeError错误
尝试从嵌套了列表与字典的JSON响应中提取hostname值时,触发TypeError: list indices must be integers or slices, not str错误,目标是生成以propertyName为键、对应hostname列表为值的字典结构。
返回的JSON示例
{ "accountId": "act_1234", "contractId": "ctr_1234", "groupId": "grp_1234", "propertyId": "prp_1234", "propertyName": "www.property.com", "propertyVersion": 1, "etag": "jbcas6764023nklf78354", "rules": { "name": "default", "children": [{ "name": "Route", "children": [], "behaviors": [{ "name": "origin", "options": { "originType": "CUSTOMER", "hostname": "www.origin.com", "forwardHostHeader": "REQUEST_HOST_HEADER" } }] }] } }
现有报错代码
#get hostnames of each property for (j, k) in itertools.zip_longest(propid, prodversion): propertyId = str(j) propertyVersion = str(k) path= '/sample/v1/properties/{}/versions/{}/rules'.format(propertyId, propertyVersion) headers = { "Accept": "application/json", "PAPI-Use-Prefixes": "true" } querystring = { "contractId": "ctr_1234", "groupId": str(i), "validateRules": "true", "validateMode": "full" } result = session.get(urljoin(baseurl, path), headers=headers, params=querystring, verify=False) hostnames = result.json() hostnameslist = [host['hostname'] for host in hostnames['rules']['children']['behaviors']['options']] print(hostnameslist)
错误原因
hostnames['rules']['children']是列表类型,无法直接通过字符串索引访问,必须使用整数下标或遍历列表元素- 每个
children元素中的behaviors同样是列表,需要遍历或下标访问其中的字典项 - 原代码直接对列表使用字符串索引,导致类型不匹配错误
修复后的代码
import itertools from urllib.parse import urljoin # 初始化结果字典 properties_hostnames = {'properties': {}} #get hostnames of each property for (j, k) in itertools.zip_longest(propid, prodversion): propertyId = str(j) propertyVersion = str(k) path= '/sample/v1/properties/{}/versions/{}/rules'.format(propertyId, propertyVersion) headers = { "Accept": "application/json", "PAPI-Use-Prefixes": "true" } querystring = { "contractId": "ctr_1234", "groupId": str(i), "validateRules": "true", "validateMode": "full" } result = session.get(urljoin(baseurl, path), headers=headers, params=querystring, verify=False) property_data = result.json() # 获取当前property的名称 prop_name = property_data['propertyName'] current_hostnames = [] # 遍历rules下的children列表 for child in property_data['rules']['children']: # 遍历每个child下的behaviors列表 for behavior in child['behaviors']: # 提取hostname并加入列表 if 'options' in behavior and 'hostname' in behavior['options']: current_hostnames.append(behavior['options']['hostname']) # 将结果存入目标字典 properties_hostnames['properties'][prop_name] = current_hostnames print(properties_hostnames)
期望输出结构
{ 'properties': { 'www.property1.com': ['www.origin1.com', 'www.origin2.com'], 'www.property2.com': ['www.origin1.com', 'www.origin2.com'] } }
内容的提问来源于stack exchange,提问作者francorocks
相关产品推荐
相关产品推荐

