Iain Iain - 1 year ago 67
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?


results in


but I need

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

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

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 Source

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.