简体   繁体   English

R将数据帧转换为JSON

[英]R convert dataframe to JSON

I have a dataframe that I'd like to convert to json format:我有一个数据框,我想将其转换为 json 格式:

my data frame called res1:我的数据框称为 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?我需要这个 json 输出是这样的,有什么想法吗?

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

The jsonlite package exists to address exactly this problem: "A practical and consistent mapping between JSON data and R objects." jsonlite包的存在正是为了解决这个问题:“JSON 数据和 R 对象之间的实用且一致的映射。”

Its toJSON function provides this desired result with the default options:它的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"}]

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.通过使用split()我们实际上是将大的 data.frame 分解为每行一个单独的 data.frame。 And by removing the names from the resulting list, the toJSON function wraps the results in an array rather than a named object.通过从结果列表中删除名称, toJSON函数将结果包装在一个数组中,而不是一个命名对象中。

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

You can also use library(jsonify)您还可以使用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"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM