rjsonhttr2

R Parsing output from JSON API


I want to retrieve data from IMF JSON RESTful Web Service API. I have found a dataset name and series code, so I submit a following request, usinng httr2 pacakge:

library(httr2)
library(tidyverse)
req <- request("http://dataservices.imf.org/REST/SDMX_JSON.svc/CompactData/IFS/PCPI_IX?startPeriod=2015&endPeriod=2020") %>% 
  req_perform()

As a result I get a list of 7 items.

How should I parse this output to get actual data? In the body item in the response there're no actual numbers. I've tried to use fromJSON from the jsonlite library but it gives me an error (Argument 'txt' must be a JSON string, URL or file).

library(jsonlite)
req <- request("http://dataservices.imf.org/REST/SDMX_JSON.svc/CompactData/IFS/PCPI_IX?startPeriod=2015&endPeriod=2020") %>% 
  req_perform() %>% 
  fromJSON()

Solution

  • There is no need to switch to {httr}

    httr is superseded: only changes necessary to keep it on CRAN will be made. We recommend using httr2 instead.

    Source: https://httr.r-lib.org/

    You can use httr2::resp_body_json

    library(httr2)
    req <- request("http://dataservices.imf.org/REST/SDMX_JSON.svc/CompactData/IFS/PCPI_IX?startPeriod=2015&endPeriod=2020")
    resp <- req |> req_perform()
    parsed_body <- resp_body_json(resp, simplifyVector = TRUE)
    parsed_body
    

    Please see this related article.

    Edit: For future readers: You might want to set simplifyVector = TRUE (coerce JSON arrays containing only primitives into an atomic vector) or simplifyDataFrame = TRUE (coerce JSON arrays containing only records (JSON objects) into a data.frame) in resp_body_json which is passed to the underlying jsonlite::fromJSON call.