将数据帧转换为json

时间:2014-08-28 13:59:49

标签: json r rjson

我有一个数据框,我想转换为json格式:

我的数据框叫做res1:

library(rjson)

structure(list(id = c(1, 2, 3, 4, 5), value = structure(1:5, .Label = c("server1", 
"server2", "server3", "server4", "server5"), class = "factor")), .Names = c("id", 
"value"), row.names = c(NA, -5L), class = "data.frame")

当我这样做时:

toJSON(res1)

我明白了:

{"id":[1,2,3,4,5],"value":["server1","server2","server3","server4","server5"]}

我需要这个json输出就像这样,有什么想法吗?

[{"id":1,"value":"server1"},{"id":2,"value":"server2"},{"id":3,"value":"server3"},{"id":4,"value":"server4"},{"id":5,"value":"server5"}]

4 个答案:

答案 0 :(得分:44)

存在jsonlite包来解决这个问题:“JSON数据和R对象之间实际且一致的映射。”

它的toJSON函数使用默认选项提供了所需的结果:

library(jsonlite)
x <- toJSON(res1)
cat(x)

## [{"id":1,"value":"server1"},{"id":2,"value":"server2"},
## {"id":3,"value":"server3"},{"id":4,"value":"server4"},
## {"id":5,"value":"server5"}]

答案 1 :(得分:20)

怎么样

library(rjson)
x <- toJSON(unname(split(res1, 1:nrow(res1))))
cat(x)
# [{"id":1,"value":"server1"},{"id":2,"value":"server2"},
# {"id":3,"value":"server3"},{"id":4,"value":"server4"},
# {"id":5,"value":"server5"}]

通过使用split(),我们基本上将大型data.frame拆分为每行的单独data.frame。通过从结果列表中删除名称,toJSON函数将结果包装在数组中而不是命名对象中。

答案 2 :(得分:1)

现在,您可以轻松地直接在数据框上调用jsonlite::write_json()

答案 3 :(得分:0)

您也可以使用library(jsonify)

jsonify::to_json( res1 )
# [{"id":1.0,"value":"server1"},{"id":2.0,"value":"server2"},{"id":3.0,"value":"server3"},{"id":4.0,"value":"server4"},{"id":5.0,"value":"server5"}]