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

如何在R和Python中将深层JSON转换为扁平化DataFrame

嵌套JSON转扁平化DataFrame解决方案

R语言实现

步骤与代码

使用jsonlite包的flatten()函数可递归展开所有嵌套结构,将多层数据转换为单一DataFrame,再通过writexl包导出至Excel:

# 加载依赖包
library(jsonlite)
library(writexl)

# 读取并提取目标数据
json_data <- jsonlite::fromJSON(txt = "https://www.itftennis.com/tennis/api/PlayerApi/GetPlayerActivity?circuitCode=WCT&matchTypeCode=S&playerId=800305047&skip=180&surfaceCode=&take=50&year=all")
json_data2 <- json_data[[1]]

# 扁平化处理
flattened_df <- flatten(json_data2, recursive = TRUE)

# 导出到Excel文件
write_xlsx(flattened_df, "flattened_player_activity.xlsx")

说明

  • recursive = TRUE参数会遍历所有嵌套层级,将深层数据提取至顶层,列名用.分隔原嵌套路径(例如opponent.playerName)。
  • write_xlsx()直接生成可在Excel中打开的文件。

Python语言实现

步骤与代码

借助pandas的json_normalize()函数处理嵌套JSON,结合requests获取数据后导出至Excel:

import pandas as pd
import requests

# 获取API数据
url = "https://www.itftennis.com/tennis/api/PlayerApi/GetPlayerActivity?circuitCode=WCT&matchTypeCode=S&playerId=800305047&skip=180&surfaceCode=&take=50&year=all"
response = requests.get(url)
json_data = response.json()
json_data2 = json_data[0]

# 扁平化转换
flattened_df = pd.json_normalize(json_data2, sep="_")

# 导出到Excel文件
flattened_df.to_excel("flattened_player_activity.xlsx", index=False)

说明

  • sep="_"指定嵌套层级的分隔符,生成的列名将用下划线区分原结构(例如opponent_playerName)。
  • index=False避免将DataFrame的索引列写入Excel,保证文件结构简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:30:57