使用 R 通过 API 自动上传 json 文件

Automatic upload json files via API using R

我想使用 API 获取财务数据。 我这样做。

#load jsons
library("rjson")
json_file <- "https://api.coindesk.com/v1/bpi/currentprice/USD.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

#get json content as data.frame
x = data.frame(json_data$time$updated,json_data$time$updatedISO,json_data$time$updateduk,json_data$bpi$USD)
x

但主要问题是信息每分钟都在变化,所以我无法收集历史记录。 有没有办法让 R 每分钟(即实时模式)独立连接到该站点并每分钟收集数据。 所以收集的数据必须保存在C:/Myfolder中。 可以吗?

像这样可以做到

library("rjson")
json_file <- "https://api.coindesk.com/v1/bpi/currentprice/USD.json"

numOfTimes <- 2L # how many times to run in total
sleepTime <- 60L  # time to wait between iterations (in seconds)
iteration <- 0L
while (iteration < numOfTimes) {
  # gather data
  json_data <- fromJSON(paste(readLines(json_file), collapse=""))
  # get json content as data.frame
  x = data.frame(json_data$time$updated,json_data$time$updatedISO,json_data$time$updateduk,json_data$bpi$USD)
  # create file to save in 'C:/Myfolder' 
  # alternatively, create just one .csv file and update it in each iteration
  nameToSave <- nameToSave <- paste('C:/Myfolder/', 
                                     gsub('\D','',format(Sys.time(),'%F%T')), 
                                    'json_data.csv', sep = '_')
  # save the file
  write.csv(x, nameToSave)
  # update counter and wait 
  iteration <- iteration + 1L
  Sys.sleep(sleepTime)
}    

请注意,这需要打开一个 R 会话(您可以创建一个 .exe.bat 文件并将其 运行 放在后台)。