如何用R将API响应数据写入结构化CSV文件?
解决方法:将API返回的JSON解析为结构化CSV
问题原因
你直接将原始JSON文本写入CSV文件,而JSON是层级格式,并非CSV要求的逗号分隔行列结构,所以Excel无法正确识别列和行。需要先把JSON解析为R的数据框,再导出为CSV。
完整实现代码
# 安装所需包(首次运行时执行) install.packages(c("httr", "jsonlite", "lubridate")) # 加载包 library(httr) library(jsonlite) library(lubridate) # 发送API请求 res <- VERB("GET", url = "https://us-central1-iattended-a2e10.cloudfunctions.net/periods?orgId&apiKey") # 解析JSON响应为R数据框 periods_df <- fromJSON(content(res, "text")) # 转换嵌套的Unix时间戳为可读日期时间 periods_df$startTime <- as_datetime(periods_df$startTime$`_seconds`) periods_df$endTime <- as_datetime(periods_df$endTime$`_seconds`) periods_df$createdOn <- as_datetime(periods_df$createdOn$`_seconds`) # 导出为结构化CSV write.csv(periods_df, "chapel.csv", row.names = FALSE)
关键步骤说明
- 解析JSON:
fromJSON(content(res, "text"))将API返回的JSON数组转换为R数据框,顶层JSON键会成为数据框的列,嵌套字段会生成列表列。 - 处理时间字段:API返回的时间是Unix秒数,用
as_datetime(lubridate包)或基础R的as.POSIXct(..., origin = "1970-01-01")转换为人类可读的日期时间格式。 - 导出CSV:
write.csv将数据框按行列结构写入文件,row.names = FALSE避免多余的行号列。
替代方案(不用lubridate)
如果不想安装lubridate,用基础R处理时间:
periods_df$startTime <- as.POSIXct(periods_df$startTime$`_seconds`, origin = "1970-01-01") periods_df$endTime <- as.POSIXct(periods_df$endTime$`_seconds`, origin = "1970-01-01") periods_df$createdOn <- as.POSIXct(periods_df$createdOn$`_seconds`, origin = "1970-01-01")
内容的提问来源于stack exchange,提问作者Matt Rehbein
相关产品推荐
相关产品推荐

