如何将含嵌套结构的API响应数据转换为pandas DataFrame
错误原因
触发列表类型错误的核心原因是字段类型判断错误:techs_assigned是列表嵌套字典的结构(一个工单可分配多名技师,因此接口用数组存储该字段),列表仅支持整数下标索引元素,不支持字符串键直接取值,直接写item['techs_assigned']['id']这类代码必然抛出类型错误。
解决方案
根据你构建DataFrame的业务需求,选对应处理方式即可:
方案1:保持单工单单行结构
如果需要每个工单对应DataFrame中的一行,可以将多技师信息处理为列表或拼接字符串存入字段,同时做空值兼容避免接口返回空值时中断程序:
import pandas as pd itemlist = [] for item in response['items']: # 容错处理:无技师分配时默认返回空列表 tech_list = item.get('techs_assigned', []) # 按需提取技师属性 tech_ids = [t['id'] for t in tech_list] tech_full_names = [f"{t['first_name']}{t['last_name']}" for t in tech_list] required = { 'status': item['status'], 'start_date': item['start_date'], 'date_created': item['created_at'], 'Job Category': item['category'], 'revenue': item['payments_deposits_total'], 'tech_ids': tech_ids, 'tech_names': tech_full_names, 'tech_concat_str': '; '.join(tech_full_names) } itemlist.append(required) # 生成DataFrame df = pd.DataFrame(itemlist)
方案2:拆分多技师为多行
如果后续需要按技师维度做统计(比如计算每个技师的工单量、营收),可以在遍历工单时嵌套遍历技师列表,让每个技师对应单独一行:
import pandas as pd itemlist = [] for item in response['items']: # 先提取工单公共字段 base_info = { 'status': item['status'], 'start_date': item['start_date'], 'date_created': item['created_at'], 'Job Category': item['category'], 'revenue': item['payments_deposits_total'] } # 无分配技师时生成仅含公共字段的行 if not item.get('techs_assigned'): itemlist.append(base_info) continue # 遍历每个技师生成单独行 for tech in item['techs_assigned']: row = base_info.copy() row['tech_id'] = tech['id'] row['tech_first_name'] = tech['first_name'] row['tech_last_name'] = tech['last_name'] itemlist.append(row) # 生成DataFrame df = pd.DataFrame(itemlist)
扩展提示
接口返回中所有数组类型的字段(包括agents、custom_fields、equipment、visits下嵌套的techs_assigned等)都遵循相同的取值逻辑:必须先遍历列表内的元素,再对单个元素做键值提取,不能直接对列表用字典键取值。用dict.get(字段名, 默认值)的写法可以兼容接口偶发的缺字段、空值场景,避免程序运行中断。
内容的提问来源于stack exchange,提问作者Zachary A. Wickard
相关产品推荐
相关产品推荐

