0

How can I convert a list to a json object using jsonlite keeping duplicated names?

z<-as.list(letters[1:3])
names(z)<-c("tmp","tmp","tmp")
toJSON(z,auto_unbox=TRUE)

results in

 {"tmp":"a","tmp.1":"b","tmp.2":"c"} 

but I need

 {"tmp": ["a", "b", "c"]}

Update: An easier solution is to bundle everything into a list

 my_list<-list()
 my_list$id<-"id"
 my_list$tmp<-c("a","b","c")
 toJSON(my_list,auto_unbox=T) # properly formatted JSON

Update: This question very nicely deals with the case of individually unboxing each JSON object encoding a JSON expression from R with jsonlite or something else

Community
  • 1
  • 1
Iain
  • 1,608
  • 4
  • 22
  • 27

1 Answers1

2

You'll have to do the object manipulation yourself to reshape your object to get the correct JSON output. To get your desired output, you'd need a named list of arrays. Here's how you can convert your data to such an object

jsonlite:::toJSON(with(stack(z), tapply(values, ind, c, simplify=FALSE)))
# {"tmp":["a","b","c"]} 

Basically stack() collapse the data into a data.frame and then we group the data into lists.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Nice. Then I can combine with other objects like this: toJSON(list(id="blah",atts=jsonlite:::toJSON(with(stack(z), tapply(values, ind, c, simplify=FALSE)))),auto_unbox = TRUE) – Iain May 05 '16 at 22:06
  • `toJSON(split(unlist(z), rep(names(z), lengths(z)) ))` as a variation, or just `toJSON(split(unlist(z), names(z)))` if there is only one value in each list item. – thelatemail May 06 '16 at 00:28