0

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

Tim
  • 929
  • 12
  • 30
  • 1
    You may want to look at `asJSVars()` and use the `.vars` argument – Rich Scriven Dec 18 '14 at 19:28
  • I don't understand what you're asking. What precisely in the input you will be using? You can convert a list to a copy/paste-able format with `dput(json_data)`. – MrFlick Dec 18 '14 at 20:04
  • Thanks MrFlick. Your comment made me re-evaluate my approach and question. Question is now restated. Richard - I will look more into the RJSONIO documentation. – Tim Dec 18 '14 at 20:31

1 Answers1

0

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}]}
jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • It is interesting to note the different format when RJSONIO is used instead of rjson: '{ "items": [ { "name": [ "Item 1" ], "group": [ 1 ] }, ...... etc. – Tim Dec 19 '14 at 15:20
  • this works well for my application. Is there a way to make the output more human-readable, with each name and group on a separate line? I will update the original question to show the format. – Tim Dec 19 '14 at 19:03