我在 R 中编写了以下代码以开始使用数据请求 API。这是一个普通的网络服务 JSON API。
library(RJSONIO)
library(RCurl)
library(httr)
r <- POST("http://api.scb.se/OV0104/v1/doris/sv/ssd/START/PR/PR0101/PR0101A/KPIFastM2",
body = '{ "query": [], "response": { "format": "json" } }')
stop_for_status(r)
a<-content(r, "text", "application/json", encoding="UTF-8")
cat(a, file = "test.json")
x<-fromJSON(file("test.json", "r"))
mydf<-do.call(rbind, lapply(x$data, data.frame))
colnames(mydf)<-c("YearMonth", "CPI")
基本上,它使用 httr 为 URL 初始化一个 get reuest,然后通过 fromJSON 将生成的 JSON 数据转换为 R 结构。 JSON 请求如下所示:
{ "query": [], "response": { "format": "json" } }
事实上,我的代码确实像我希望的那样将数据放入 data.frame 中,但它冗长得令人痛苦,我拒绝相信所有这些行都是实现所需结果所必需的。想要的结果当然是 mydf data.frame。
那么我的问题是:从 Web 服务获取数据到 data.frame 的最短和最正确的方法是什么?
干杯, 迈克尔
最佳答案
有两个问题。一个是您没有使用 jsonlite :-) 另一个是您的 JSON 源似乎在 blob 前加上了 U+FEFF
Byte order Mark使 JSON 无效的字符。 RFC7159说:
Implementations MUST NOT add a byte order mark to the beginning of a JSON text. In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.
所以 scb.se 没有正确格式化他们的 JSON。无论哪种方式,试试这个:
library(jsonlite)
library(httr)
req <- POST("http://api.scb.se/OV0104/v1/doris/sv/ssd/START/PR/PR0101/PR0101A/KPIFastM2",
body = '{ "query": [], "response": { "format": "json" } }')
stop_for_status(req)
json <- content(req, "text")
# JSON starts with an invalid character:
validate(json)
json <- substring(json, 2)
validate(json)
# Now we can parse
object <- jsonlite::fromJSON(json)
print(objects)
关于json - 如何以更简洁的方式将 JSON 格式的请求从 R 中的 URL 获取 JSON 数据发送到 data.frame 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693842/