How to make POST for a formatted JSON request to get GET JSON data from a URL in R in data.frame in a less detailed way?

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

+2
1

. , jsonlite:-) , JSON, , blob U+FEFF Byte order Mark, JSON . RFC7159 :

JSON. , JSON, , .

, 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)
+6

Source: https://habr.com/ru/post/1670276/


All Articles