问题描述
我在 R 中编写了以下代码以开始使用数据请求 API.这是一个普通的 Web 服务 JSON API.
I have written the following code in R to start using a data request API. It's a normal web service 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 请求如下所示:
Basically it initialized a get reuest for the URL using httr and then convert the resulting JSON data to an R structure via fromJSON. The JSON request looks like this:
{ "query": [], "response": { "format": "json" } }
确实,我的代码按照我的意愿将数据放入 data.frame 中,但它非常冗长,而且我拒绝相信所有这些行都是实现预期结果所必需的.想要的结果当然是 mydf data.frame.
Indeed my code gets the data into a data.frame like I wanted it to, but it is painfully verbose and I refuse to believe that all of these lines are necessary to achieve the wanted result. The wanted result is the mydf data.frame of course.
那么对于我的问题:从 Web 服务获取数据到 data.frame 的最短和最正确的方法是什么?
So to my question: What is the shortest and most correct way to get the data from the web service into the data.frame?
干杯,迈克尔
推荐答案
有两个问题.一个是您没有使用 jsonlite :-) 另一个是您的 JSON 源似乎在 blob 前面加上了 U+FEFF
字节顺序标记 使 JSON 无效的字符.RFC7159 说:
There are two problems. One is that you are not using jsonlite :-) The other one is that your JSON source seems to prefix the blob with a U+FEFF
Byte order Mark character that makes the JSON invalid. RFC7159 says:
实现不得在 JSON 文本的开头添加字节顺序标记.为了互操作性,解析 JSON 文本的实现可能会忽略字节顺序标记的存在,而不是将其视为错误.
所以 scb.se 没有正确格式化他们的 JSON.不管怎样,试试这个:
So scb.se is not formatting their JSON correctly. Either way, try this:
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 格式的请求以从 R 中的 URL 获取 JSON 数据到 data.frame 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!