简体   繁体   English

如何以较简洁的方式将JSON格式的请求从R中的URL中的GET JSON数据发布到data.frame中?

[英]How do I POST a JSON formatted request to GET JSON data from a URL in R into the data.frame in a less verbose manner?

I have written the following code in R to start using a data request API. 我在R中编写了以下代码以开始使用数据请求API。 It's a normal web service JSON API. 这是一个普通的Web服务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")

Basically it initialized a get reuest for the URL using httr and then convert the resulting JSON data to an R structure via fromJSON. 基本上它使用httr初始化URL的get reuest,然后通过fromJSON将生成的JSON数据转换为R结构。 The JSON request looks like this: JSON请求如下所示:

{ "query": [], "response": { "format": "json" } }

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. 想要的结果当然是mydf 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? 所以我的问题是:从Web服务获取数据到data.frame的最短和最正确的方法是什么?

Cheers, Michael 干杯,迈克尔

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. 一个是你没有使用jsonlite :-)另一个是你的JSON源似乎在blob前面加上一个U+FEFF 字节顺序Mark字符使得JSON无效。 RFC7159 says: RFC7159说:

Implementations MUST NOT add a byte order mark to the beginning of a JSON text. 实现绝不能在JSON文本的开头添加字节顺序标记。 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. 为了互操作性,解析JSON文本的实现可以忽略字节顺序标记的存在,而不是将其视为错误。

So scb.se is not formatting their JSON correctly. 所以scb.se没有正确格式化他们的JSON。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM