我正在尝试找出从 R 生成 JSON 文件的最佳方法。我有以下数据框 tmp
在R
.
> tmp
gender age welcoming proud tidy unique
1 1 30 4 4 4 4
2 2 34 4 2 4 4
3 1 34 5 3 4 5
4 2 33 2 3 2 4
5 2 28 4 3 4 4
6 2 26 3 2 4 3
tmp <- data.frame(
gender = c(1L, 2L, 1L, 2L, 2L, 2L),
age = c(30, 34, 34, 33, 28, 26),
welcoming = c(4L, 4L, 5L, 2L, 4L, 3L),
proud = c(4L, 2L, 3L, 3L, 3L, 2L),
tidy = c(4L, 4L, 4L, 2L, 4L, 4L),
unique = c(4L, 4L, 5L, 4L, 4L, 3L)
)
使用rjson
包,我运行 toJSON(tmp)
行它会生成以下 JSON 文件:
{"gender":[1,2,1,2,2,2],
"age":[30,34,34,33,28,26],
"welcoming":[4,4,5,2,4,3],
"proud":[4,2,3,3,3,2],
"tidy":[4,4,4,2,4,4],
"unique":[4,4,5,4,4,3]}
我还尝试了 RJSONIO
包裹; toJSON()
的输出是一样的。我想要生成的是以下结构:
{"traits":["gender","age","welcoming","proud", "tidy", "unique"],
"values":[
{"gender":1,"age":30,"welcoming":4,"proud":4,"tidy":4, "unique":4},
{"gender":2,"age":34,"welcoming":4,"proud":2,"tidy":4, "unique":4},
....
]
我不知道如何最好地做到这一点。我意识到我可以使用 python
逐行解析它但我觉得可能有更好的方法来做到这一点。我还意识到我的数据结构在 R
没有反射(reflect)我的 JSON
中所需的元信息文件(特别是 traits
行),但我主要感兴趣的是生成类似于该行的格式的数据
{"gender":1,"age":30,"welcoming":4,"proud":4,"tidy":4, "unique":4}
因为我可以手动添加第一行。
<小时/>编辑:我发现了一个有用的 blog作者在帖子中处理了类似的问题并提供了解决方案。此函数从数据帧生成格式化的 JSON 文件。
toJSONarray <- function(dtf){
clnms <- colnames(dtf)
name.value <- function(i){
quote <- '';
# if(class(dtf[, i])!='numeric'){
if(class(dtf[, i])!='numeric' && class(dtf[, i])!= 'integer'){ # I modified this line so integers are also not enclosed in quotes
quote <- '"';
}
paste('"', i, '" : ', quote, dtf[,i], quote, sep='')
}
objs <- apply(sapply(clnms, name.value), 1, function(x){paste(x, collapse=', ')})
objs <- paste('{', objs, '}')
# res <- paste('[', paste(objs, collapse=', '), ']')
res <- paste('[', paste(objs, collapse=',\n'), ']') # added newline for formatting output
return(res)
}
最佳答案
使用包jsonlite
:
> jsonlite::toJSON(list(traits = names(tmp), values = tmp), pretty = TRUE)
{
"traits": ["gender", "age", "welcoming", "proud", "tidy", "unique"],
"values": [
{
"gender": 1,
"age": 30,
"welcoming": 4,
"proud": 4,
"tidy": 4,
"unique": 4
},
{
"gender": 2,
"age": 34,
"welcoming": 4,
"proud": 2,
"tidy": 4,
"unique": 4
},
{
"gender": 1,
"age": 34,
"welcoming": 5,
"proud": 3,
"tidy": 4,
"unique": 5
},
{
"gender": 2,
"age": 33,
"welcoming": 2,
"proud": 3,
"tidy": 2,
"unique": 4
},
{
"gender": 2,
"age": 28,
"welcoming": 4,
"proud": 3,
"tidy": 4,
"unique": 4
},
{
"gender": 2,
"age": 26,
"welcoming": 3,
"proud": 2,
"tidy": 4,
"unique": 3
}
]
}
关于json - R 格式化 JSON 输出的策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288925/