Question

I have an issue with RJSONIO. I have a data frame like df

df <- data.frame(a = c(1:3), b = c(4:6), c = c(7:9) )
df
  a b c
1 1 4 7
2 2 5 8
3 3 6 9

Now what I need is to use this data frame and generate the rows in the following JSON structure. So in the end it would look something like this:

{
"job_id": "1",
"page": "1",
"rows": [
    {
        "row": [
            "1",
            "4",
            "7"
        ]
    },
    {
        "row": [
            "2",
            "5",
            "8"
        ]
    },
    {
        "row": [
            "3",
            "6",
            "9"
        ]
    }
]

}

I started with this chunk of code but there is problem with quotes inside the array (surrounding curly brackets):

rows <- apply(df, 1, function(x) toJSON(list(row = x)) )
toJSON(list("job_id" = "1",  "page" = "1", "rows" = paste(rows) ) )

Thanks for any advice!

Was it helpful?

Solution

Here how you create your JSON format.

list(job_id = "1", 
   page = "1", 
   rows = lapply(seq(nrow(df)), function(x) list(row=as.character(df[x,]))))


cat(toJSON(ll))
{"job_id": "1",
 "page": "1",
 "rows": [
  {
   "row": [ "1", "4", "7" ] 
  },
  {
   "row": [ "2", "5", "8" ] 
  },
  {
   "row": [ "3", "6", "9" ] 
  } 
 ] 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top