将 JSON 对象保存到 file.JSON [英] Saving a JSON object to file.JSON
问题描述
我已经创建了一个 JSON 文件,我需要能够通过电子邮件与其他协作者共享该文件.然而,尽管在 R 工作区中处理 JSON 对象有很多可用的主题,但几乎没有资源讨论如何将 JSON 对象实际导出到 .JSON 文件.
I've create a JSON file, and I need to be able to share the file via email with other collaborators. However, although there are plenty of topics available on handling JSON objects in the R workspace, there are virtually no resources discussing how to actually export a JSON object to a .JSON file.
这是一个简单的例子:
list1 <- vector(mode="list", length=2)
list1[[1]] <- c("a", "b", "c")
list1[[2]] <- c(1, 2, 3)
exportJson <- toJSON(list1)
## Save the JSON to file
save(exportJson, file="export.JSON")
## Attempt to read in the JSON
library("rjson")
json_data <- fromJSON(file="export.JSON")
尝试读取 JSON 文件的最后一行导致错误:Error in fromJSON(file = "export.JSON") : 意外字符 'R'"
The final line, attempting to read in the JSON file, results in an error: "Error in fromJSON(file = "export.JSON") : unexpected character 'R'"
显然 save() 函数不是可行的方法,但是经过大量的谷歌搜索后,我没有发现任何说明如何将 JSON 导出到文件的内容.任何帮助将不胜感激.
Obviously the save() function is not the way to go, but after extensive googling, I have found nothing that says how to export the JSON to a file. Any help would be greatly appreciated.
推荐答案
可以使用write
:
library(RJSONIO)
list1 <- vector(mode="list", length=2)
list1[[1]] <- c("a", "b", "c")
list1[[2]] <- c(1, 2, 3)
exportJson <- toJSON(list1)
> exportJson
[1] "[
[ "a", "b", "c" ],
[ 1, 2, 3 ]
]"
write(exportJson, "test.json")
library("rjson")
json_data <- fromJSON(file="test.json")
> json_data
[[1]]
[1] "a" "b" "c"
[[2]]
[1] 1 2 3
这篇关于将 JSON 对象保存到 file.JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!