Create a list in a specific format? [ Or: Create a JSON file with specific format]

78 views Asked by At

I am trying to create a JSON file with a specific format. My original approach was to reverse engineer the process by reading in a source JSON file using JSONIO, examining the resulting R list element and trying to recreate that list element with my own source data for use in toJSON. That approach was needlessly complex. My restated problem is:

I want to create this JSON file:

{
 "items":[
   {"name":"Item 1","group":1},
   {"name":"Item 2","group":1},
   {"name":"Item 3","group":2},
 ]
}

From this input data:

name    group
"Item 1"   1
"Item 2"   1
"Item 3"   2

I will now focus more on the RJSONIO documentation. I was previously focused on recreating the R list with my data instead of learning more about RJSONIO. Apologies for the misdirection.

The code snippet provided by @jlhoward below works well and is read by my application correctly. Is there a way to make the JSON more human-readable as in:

{
 "items":[
   {"name":"Item 1","group":1},
   {"name":"Item 2","group":1},
   {"name":"Item 3","group":2},
]}

Tim

1

There are 1 answers

2
jlhoward On

Calling your data frame df

library(rjson)
result <- toJSON(list(items=lapply(1:nrow(df),function(i)df[i,])))
cat(result)
# {"items":[{"name":"Item 1","group":1},{"name":"Item 2","group":1},{"name":"Item 3","group":2}]}