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?

后端 未结 1 1588
花落未央
花落未央 2020-12-20 02:52

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)
         


        
相关标签:
1条回答
  • 2020-12-20 03:29

    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:

    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.

    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)
    
    0 讨论(0)
提交回复
热议问题