将数据帧转换为json [英] convert data frame to json
本文介绍了将数据帧转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,我想将其转换为json格式:
I have a data frame that I 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.
这篇关于将数据帧转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文