Iain Iain - 5 months ago 25
JSON Question

Keep duplicated names in json object from jsonlite conversion of list

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

Answer

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.