将JSON对象保存到file.JSON [英] Saving a JSON object to file.JSON

查看:159
本文介绍了将JSON对象保存到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文件的最后一行导致错误: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.

推荐答案

您可以使用

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] "[\n [ \"a\", \"b\", \"c\" ],\n[      1,      2,      3 ] \n]"
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆