You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将领英API多层嵌套JSON转换为指定结构CSV文件

你当前的问题出在自定义的flatten函数将整个JSON包括elements数组的所有条目都压缩为了单个扁平字典,最终自然只会输出单行数据。你不需要自定义扁平化逻辑,直接使用pandas内置的json_normalize处理elements数组即可,代码如下:

import json
import pandas as pd

# 读取JSON文件
with open('C:/Users/Muj/Downloads/Linkedin data/follower_statistics_per_day.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# 直接对elements数组做标准化展开
df = pd.json_normalize(data['elements'])

# 筛选需要的列并重命名,去掉嵌套前缀
df = df[['followerGains.organicFollowerGain', 'followerGains.paidFollowerGain', 'organizationalEntity']]
df.columns = ['organicFollowerGain', 'paidFollowerGain', 'organizationalEntity']

# 导出CSV
df.to_csv('C:/Users/Muj/Downloads/Linkedin data/test1.csv', index=False)

运行后生成的CSV就完全符合你预期的结构,每个elements数组里的条目对应一行,三列分别对应自然新增粉丝数、付费新增粉丝数、机构ID。如果需要保留timeRange等其他字段,只需要在筛选列时加上对应字段名即可。

内容的提问来源于stack exchange,提问作者Krouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:45:04