I wrote the following code in R to start using the data query API. This is a regular JSON API web service.
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, he initialized receiving the request for the URL using httr, and then converted the received JSON data to an R structure via fromJSON. The JSON request is as follows:
{ "query": [], "response": { "format": "json" } }
Indeed, my code receives data in data.frame as I wanted it, but it is painfully verbose, and I refuse to believe that all these lines are necessary to achieve the desired result. The desired result is the mydf data.frame file, of course.
So, to my question: what is the shortest and most correct way to get data from a web service in data.frame?
Cheers, Michael