Parsing data frame to JSON (via RJSONIO)

核能气质少年 提交于 2019-12-08 02:06:31

问题


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!


回答1:


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" ] 
  } 
 ] 
}


来源:https://stackoverflow.com/questions/15116072/parsing-data-frame-to-json-via-rjsonio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!