R将数据帧转换为JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25550711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:30:39  来源:igfitidea点击:

R convert dataframe to JSON

rjsondataframerjson

提问by user1471980

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

采纳答案by MrFlick

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 toJSONfunction wraps the results in an array rather than a named object.

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

回答by nycdatawrangler

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

所述jsonlite包是否存在于地址恰好此问题:“JSON数据和R对象之间的实际和一致映射”。

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

回答by Jared Wilber

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

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

回答by SymbolixAU

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