Search code examples
rstringifyjsonlite

In R, convert list into stringified JSON for body of POST request


output_goal <- '{ "firstName": "Tim", "lastName": "Jones", "team": { "value":104290, "teamMarket": "Card", "gender": "MALE" }}'

zed1 <- list(firstName = 'Tim', lastName = 'Jones', team = list(value = 104290, teamMarket = 'Card', gender = 'MALE'))
output <- jsonlite::toJSON(zed1)
output <- gsub('\\[', '', output)
output <- gsub('\\]', '', output)
output == output_goal
> FALSE


zed2 <- list(firstName = 'Tim', lastName = 'Jones', team = data.frame(value = 104290, teamMarket = 'Card', gender = 'MALE'))
output <- jsonlite::toJSON(zed2)
output <- gsub('\\[', '', output)
output <- gsub('\\]', '', output)
output == output_goal
> FALSE

Our goal is to convert either of zed1, zed2 into the string output_goal. So far, we have tried to use jsonlite::toJSON, and then gsub to remove the brackets. I believe that we are struggling with escape characters, but am not sure what else to try to get these strings to match.


Solution

  • Take a look at the auto_unbox parameter:

    auto_unbox: Automatically unbox() all atomic vectors of length 1.

    jsonlite::toJSON(zed1, auto_unbox = TRUE)
    # {"firstName":"Tim","lastName":"Jones","team":{"value":104290,"teamMarket":"Card","gender":"MALE"}} 
    

    Note the warning in the docs though:

    It is usually safer to avoid this and instead use the unbox() function to unbox individual elements. An exception is that objects of class AsIs (i.e. wrapped in I()) are not automatically unboxed. This is a way to mark single values as length-1 arrays.

    Depending on the complexity of your real data you may want to use unbox() function on those elements you know are length one.