convert data frame to json

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 12:26:33

问题


I have a data frame that I like to convert to json format:

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\")

when I do:

toJSON(res1)

I get this:

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

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\"}]

回答1:


How about

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"}]

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.




回答2:


The jsonlite package exists to address exactly this problem: "A practical and consistent mapping between JSON data and R objects."

Its toJSON function provides this desired result with the default options:

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"}]



回答3:


Now you can easily just call jsonlite::write_json() directly on the dataframe.




回答4:


You can also use 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"}]


来源:https://stackoverflow.com/questions/25550711/convert-data-frame-to-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!