Python处理API返回嵌套JSON并生成扁平化字段的pandas DataFrame方法
嵌套API JSON转目标结构DataFrame实现
匹配需求的处理规则
- 保留原始结构顶层的
id作为独立主列 - 将嵌套在
properties节点下的所有字段全部提升到外层,无嵌套路径前缀 - 从
associations节点的嵌套结果中提取关联ID,自定义重命名为associated_deal_id,和主ID做区分
完整可运行代码
import pandas as pd from pandas import json_normalize # 原始API返回的JSON结构 raw_data = [ { 'archived': False, 'associations': { 'deals': { 'results': [ {'id': '2762673039', 'type': 'line_item_to_deal'} ] } }, 'createdAt': '2020-08-06T15:05:23.253Z', 'id': '762434477', 'properties': { 'amount': '100', 'createdate': '2020-08-06T15:05:23.253Z', 'hs_lastmodifieddate': '2020-08-06T15:05:53.701Z', 'hs_object_id': '762434477', 'hs_product_id': '133248644', 'quantity': '1' }, 'updatedAt': '2020-08-06T15:05:53.701Z' } ]
# 1. 展平嵌套字段:直接映射properties下的子字段为外层列名 df = json_normalize( raw_data, sep='__', meta=[ # 保留顶层基础字段 'id', 'archived', 'createdAt', 'updatedAt', # 拆解properties嵌套层字段,直接对应外层列名 ['properties', 'amount'], ['properties', 'createdate'], ['properties', 'hs_lastmodifieddate'], ['properties', 'hs_object_id'], ['properties', 'hs_product_id'], ['properties', 'quantity'] ] ) # 2. 提取associations下的关联ID并重命名 df['associated_deal_id'] = df['associations__deals__results'].apply( lambda res_list: res_list[0]['id'] if res_list else None ) # 3. 清理残留的嵌套路径中间列 df = df.drop(columns=['associations__deals__results'])
最终DataFrame列结构
- 主标识列:
id,取值对应原始JSON顶层的记录ID - 属性列:
amount、createdate、hs_lastmodifieddate、hs_object_id、hs_product_id、quantity,全部来自原properties嵌套节点 - 关联列:
associated_deal_id,从原associations.deals.results路径提取的关联Deal ID,已完成重命名
适配多关联场景调整:如果单条记录存在多个关联Deal,可将提取逻辑修改为逗号拼接所有关联ID:
lambda res_list: ','.join([item['id'] for item in res_list])
内容的提问来源于stack exchange,提问作者Jacob Bayer
相关产品推荐
相关产品推荐

