将数据表转换为R中的一组JSON对象

时间:2014-09-12 05:52:53

标签: json r

我想将R中的数据表转换为一组json对象: 假设我的数据表看起来像这样:

name           group    age (y) height (cm) weight (kg) score
[1,] "Doe, John"    "Red"    "24"    "182"       "74.8"      NA   
[2,] "Doe, Jane"    "Green"  "30"    "170"       "70.1"      "500"
[3,] "Smith, Joan"  "Yellow" "41"    "169"       "60"        NA   
[4,] "Brown, Sam"   "Green"  "22"    "183"       "75"        "865"
[5,] "Jones, Larry" "Green"  "31"    "178"       "83.9"      "221"
[6,] "Murray, Seth" "Red"    "35"    "172"       "76.2"      "413"
[7,] "Doe, Jane"    "Yellow" "22"    "164"       "68"        "902"

我想要如下:

[{"name":"Doe, John","group":"Red","age (y)":24,"height (cm)":182,"weight (kg)":74.8,"score":null},
{"name":"Doe, Jane","group":"Green","age (y)":30,"height (cm)":170,"weight (kg)":70.1,"score":500},
{"name":"Smith, Joan","group":"Yellow","age (y)":41,"height (cm)":169,"weight (kg)":60,"score":null},
{"name":"Brown, Sam","group":"Green","age (y)":22,"height (cm)":183,"weight (kg)":75,"score":865},
{"name":"Jones, Larry","group":"Green","age (y)":31,"height (cm)":178,"weight (kg)":83.9,"score":221},
{"name":"Murray, Seth","group":"Red","age (y)":35,"height (cm)":172,"weight (kg)":76.2,"score":413},
{"name":"Doe, Jane","group":"Yellow","age (y)":22,"height (cm)":164,"weight (kg)":68,"score":902}]

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您确定data.table输出了吗? [1,]对我来说很有趣。我认为data.table通常会1:。这看起来更像是matrix输出。

但假设它是一个像

这样的data.table
dd<-data.table(
    name = c("Doe, John", "Doe, Jane", "Smith, Joan", "Brown, Sam",
        "Jones, Larry", "Murray, Seth", "Doe, Jane"), 
    group = c("Red", "Green", "Yellow", "Green", "Green", "Red", "Yellow"), 
    "age (y)" = c(24L, 30L, 41L, 22L, 31L, 35L, 22L),
    "height (cm)" = c(182L, 170L, 169L, 183L, 178L, 172L, 164L), 
    "weight (kg)" = c(74.8, 70.1, 60, 75, 83.9, 76.2, 68), 
    score = c(NA, 500L, NA, 865L, 221L, 413L, 902L)
)

然后你可以运行

cat( toJSON( unname(split(dd, 1:nrow(dd))) ) )

获得所需的输出。

答案 1 :(得分:0)

您可以尝试在fromJSON包上使用toJSONjsonlite

library(jsonlite)

iris2 <- fromJSON(myjson)

myjson <- toJSON(iris, pretty=TRUE)
希望它有所帮助。