将R数据帧转换为json对象

时间:2015-09-11 22:50:31

标签: json r

说我有以下数据帧:

df1 <- data.frame(Name = c("Harry","George"), color=c("#EA0001", "#EEEEEE"))

    Name   color
1  Harry #EA0001
2 George #EEEEEE


df.details <- data.frame(Name = c(rep("Harry",each=3), rep("George", each=3)),
                         age=21:23,
                         total=c(14,19,24,1,9,4)
                         )


    Name age total
1  Harry  21    14
2  Harry  22    19
3  Harry  23    24
4 George  21     1
5 George  22     9
6 George  23     4

我知道如何将每个df转换为json,如下所示:

library(jsonlite)
toJSON(df.details)
[{"Name":"Harry","age":21,"total":14},{"Name":"Harry","age":22,"total":19},{"Name":"Harry","age":23,"total":24},{"Name":"George","age":21,"total":1},{"Name":"George","age":22,"total":9},{"Name":"George","age":23,"total":4}] 

但是,我希望将以下结构添加到我的JSON数据中:

{
"myjsondata": [

{
"Name": "Harry", 
"color": "#EA0001", 
"details": [
  {
    "age": 21, 
    "total": 14
  }, 
  {
    "age": 22, 
    "total": 19
  }, 
  {
    "age": 23, 
    "total": 24
  }
  ]
}, 
{
  "Name": "George", 
  "color": "#EEEEEE", 
  "details": [
    {
      "age": 21, 
      "total": 1
    }, 
    {
      "age": 22, 
      "total": 9
    }, 
    {
      "age": 23, 
      "total": 4
    }
    ]
}

]
}

我认为答案可能在于如何在转换前将数据存储在R中的列表中,但不确定。

1 个答案:

答案 0 :(得分:3)

请尝试以下格式:

df1$details <- split(df.details[-1], df.details$Name)[df1$Name]
df1
#    Name   color                details
#1  Harry #EA0001 21, 22, 23, 14, 19, 24
#2 George #EEEEEE    21, 22, 23, 1, 9, 4

toJSON(df1)
#[{
#"Name":"Harry",
#"color":"#EA0001",
#"details":[
#  {"age":21,"total":14},
#  {"age":22,"total":19},
#  {"age":23,"total":24}]},
#{
#"Name":"George",
#"color":"#EEEEEE",
#"details":[
#  {"age":21,"total":1},
#  {"age":22,"total":9},
#  {"age":23,"total":4}]}
#]