7

I am trying to encode R lists into json using the jsonlite package and the toJSON function. I have a simple item like:

list(op='abc')

I'd like that to become:

{
  "op" : "abc"
}

Instead, I get:

{
  "op" : ["abc"]
}

The API to which I am trying to feed this json chokes on the latter and requires the former. Any suggestions on how to get the former behavior from jsonlite (or another R json package)?

seandavi
  • 2,667
  • 4
  • 21
  • 41
  • 1
    Try `rjson` package. It is giving the former. – Psidom Jul 10 '16 at 02:56
  • That works. Any suggestions on how to get that behavior from the jsonlite package, which seems to have better performance? – seandavi Jul 10 '16 at 02:59
  • 1
    I think it depends on your data. It seems that if your original data is a data frame, it will also gives the former. Can your data be converted to a data frame properly? – Psidom Jul 10 '16 at 03:04
  • Unfortunatelly `rjson` has problems when saving to JSON file with diacritic characters. – Karol Daniluk Feb 19 '19 at 18:05

1 Answers1

7

The auto_unbox argument does the trick with the jsonlite package:

toJSON(list(op='abc'),auto_unbox=TRUE)

yields:

{"op":"abc"}

Update: based on comment, this approach is probably safer, and an example of why:

> jsonlite::toJSON(list(x=unbox(1),y=c(1,2)))
{"x":1,"y":[1,2]} 
> jsonlite::toJSON(list(x=unbox(1),y=unbox(c(1,2)))) # expect error here.
Error: Tried to unbox a vector of length 2
seandavi
  • 2,667
  • 4
  • 21
  • 41
  • 2
    _"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."_ – hrbrmstr Jul 10 '16 at 03:23
  • What if my list is R object, and these elements I want to unbox are 4 levels deep in the list? – Karol Daniluk Feb 19 '19 at 18:24