jsonrlistjsonlite

Using jsonlite to write an unnamed list from R into a json array


I'm sending data to a C# developer who wants to use http://json2csharp.com/ to convert my data string into an array of objects. I thought that the jsonlite package would be good for this, but he's not getting the results he wants, and as I examine the produced output, its not quite what I'd expect. My interpretation of the situation was that the output generated by

x <- list( 
  a=list( a=1,b='x',c=list("Foo","Bar"), d=as.Date("2015-01-01") ),
  b=list( a=2,b='y',c=list("Hello","World"), d=as.Date("2014-12-31") ),
  c=list( a=3,b='z',c=NULL, d=as.Date("2016-02-29") )
)
toJSON(x, pretty = FALSE )

was

{"a":{"a":[1],"b":["x"],"c":[["Foo"],["Bar"]],"d":["2015-01-01"]},"b":{"a":[2],"b":["y"],"c":[["Hello"],["World"]],"d":["2014-12-31"]},"c":{"a":[3],"b":["z"],"c":{},"d":["2016-02-29"]}} 

which put all the child element data into lists, while considering the parent named list to be an object of named elements. R doesn't have the same kind of typing that JSON was designed for, so this is probably the intended behaviour of toJSON, but I wanted something more like

[{"a":1,"b":"x","c":["Foo","Bar"],"d":"2015-01-01"},{"a":2,"b":"y","c":["Hello","World"],"d":"2014-12-31"},{"a":3,"b":"z","c":{},"d":"2016-02-29"}] 

How does one write a list in R to a JSON array in jsonlite?


Solution

  • So it turns out that unnaming the list and setting auto_unbox was what I was looking for. Changing the code to:

    x2 <- list( 
      list( a=1,b='x',c=list("Foo","Bar"), d=as.Date("2015-01-01") ),
      list( a=2,b='y',c=list("Hello","World"), d=as.Date("2014-12-31") ),
      list( a=3,b='z',c=NULL, d=as.Date("2016-02-29") )
    )
    toJSON(x2, auto_unbox = TRUE, pretty = FALSE )
    

    OR

    x2 <- unname(x)
    toJSON(x2, auto_unbox = TRUE, pretty = FALSE )
    

    resulted in the array of objects that I was looking for:

    [{"a":1,"b":"x","c":["Foo","Bar"],"d":"2015-01-01"},{"a":2,"b":"y","c":["Hello","World"],"d":"2014-12-31"},{"a":3,"b":"z","c":{},"d":"2016-02-29"}] 
    

    I couldn't name them, though.