我有一个R数据框,我想将其转换为JSON,但我想将每一行插入到名为“ traits”的新JSON对象中。我试图将traits列绑定为第一列,并将新的数据框转换为JSON,但这不会产生正确的输出。我还尝试将“ traits”:{对象添加到每个转换后的JSON输出,但这也失败了。我试图在数据框内工作,然后将其转换为JSON,因为toJSON会在方括号[]中产生一个列表,我也无法解决。我正在使用jsonlite
color = c('red','blue','green')
fruit = c('apple','orange','grape')
animal = c('cat','dog','chicken')
df<- data.frame(color, fruit, animal)
toJSON(df, pretty= TRUE)
我希望它看起来像这样:
[
{ "traits": {
"color": "red",
"fruit": "apple",
"animal": "cat"
}
},
答案 0 :(得分:2)
这是一种方法:
L <- list(list(traits = as.list(df[1,])),
list(traits = as.list(df[2,])),
list(traits = as.list(df[3,])))
> toJSON(L, pretty = TRUE, auto_unbox = TRUE)
[
{
"traits": {
"color": "red",
"fruit": "apple",
"animal": "cat"
}
},
{
"traits": {
"color": "blue",
"fruit": "orange",
"animal": "dog"
}
},
{
"traits": {
"color": "green",
"fruit": "grape",
"animal": "chicken"
}
}
]
要获取此列表L
,您可以
L <- apply(df, 1, function(x) list(traits = as.list(x)))
另一种方法是:
df2 <- purrr::transpose(lapply(df, function(x) as.character(x)))
L <- lapply(df2, function(x) list(traits = x))
或
df <- data.frame(color, fruit, animal, stringsAsFactors = FALSE)
L <- lapply(purrr::transpose(df), function(x) list(traits = x))