本文介绍了R将数据帧转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个要转换为json格式的数据框:
I have a dataframe that I'd like to convert to json format:
我的数据框称为res1:
my data frame called 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输出像这样,有什么想法吗?
I need this json output to be like this, any ideas?
[{"id":1,"value":"server1"},{"id":2,"value":"server2"},{"id":3,"value":"server3"},{"id":4,"value":"server4"},{"id":5,"value":"server5"}]
推荐答案
怎么样
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
函数将结果包装在数组中,而不是命名对象中。
By using split()
we are essentially breaking up the large data.frame into a separate data.frame for each row. And by removing the names from the resulting list, the toJSON
function wraps the results in an array rather than a named object.
这篇关于R将数据帧转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!