skip to Main Content

I have to convert a JSON string into a R object, add some information and convert it back to a JSON string.

I managed to use the package jsonlite on simple examples but now I have an issue with the "not so complex" string
{"A":["a"], "B":true}, ie if I do:

jsonlite::toJSON (jsonlite::fromJSON ('{"A":["a"], "B":true}') )

then I get:

{"A":["a"], "B":[true]}

which is not the same as the initial string since the second value has been put into a vector.

My question is:
is there a way to make jsonlite get back to the initial string ?

2

Answers


  1. You would have to alter the object. Pretty much everything in R is a vector. So when you have character values and logical values, those are all vectors. When you are making JSON strings, you can either set it to "auto unbox" vectors of length 1 to not use array brackets or you have have all vectors use array brackets. Since you want different behaviors for the string values and the logical values, there’s no way for toJSON to guess what you want.

    You can be more explicit using the unbox() function

    jsonlite::toJSON(list(A = "a", B = jsonlite::unbox(TRUE)))
    # {"A":["a"],"B":true} 
    

    Here we explictly unbox the B value.

    Login or Signup to reply.
  2. For this specific case, you could set the toJSON’s auto_unbox to TRUE and the fromJSON’s simplifyVector to FALSE.

    jsonlite::toJSON (x = jsonlite::fromJSON ('{"A":["a"], "B":true}', 
                                              simplifyVector = FALSE), 
                      auto_unbox = TRUE)
    
    #{"A":["a"],"B":true} 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search