尝试将 JSON 转换为 R 中的数据帧时出错

问题描述 投票:0回答:1

当我在 R 中运行以下代码时,我不断收到错误。

earnings_pull <- as.data.frame(rjson::fromJSON(file=paste("https://api.twelvedata.com/earnings?symbol=", "AAPL", "&outputsize=1&apikey=", twelve_data_api, sep="")))

我收到以下错误:

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 1, 0

这就是 JSON 中的数据:

{"meta":{"symbol":"AAPL","name":"Apple Inc","currency":"USD","exchange":"NASDAQ","mic_code":"XNGS","exchange_timezone":"America/New_York"},"earnings":[{"date":"2025-10-29","time":"Time Not Supplied","eps_estimate":null,"eps_actual":null,"difference":null,"surprise_prc":null}],"status":"ok"}

请帮忙。

r json dataframe api
1个回答
0
投票

解析后的 JSON 对象会变成一个列表,您可以从中提取两个数据帧,如下所示:

library(jsonlite)

my_json <- '{"meta":{"symbol":"AAPL","name":"Apple Inc","currency":"USD","exchange":"NASDAQ","mic_code":"XNGS","exchange_timezone":"America/New_York"},"earnings":[{"date":"2025-10-29","time":"Time Not Supplied","eps_estimate":null,"eps_actual":null,"difference":null,"surprise_prc":null}],"status":"ok"}'

my_df_list <- fromJSON(my_json)

meta_df <- as.data.frame(my_df_list$meta)

earnings_df <- as.data.frame(my_df_list$earnings)
© www.soinside.com 2019 - 2024. All rights reserved.