Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a JSON object to file.JSON

Tags:

json

io

r

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.

Here's a simple example:

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

The final line, attempting to read in the JSON file, results in an error: "Error in fromJSON(file = "export.JSON") : unexpected character 'R'"

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.

like image 950
Nathan Calverley Avatar asked Jul 09 '14 19:07

Nathan Calverley


People also ask

How do I save a JSON object to a file in python?

Method 2: Writing JSON to a file in Python using json.dump() Another way of writing JSON to a file is by using json. dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.

How do I save and create a JSON file?

Open a Text editor like Notepad, Visual Studio Code, Sublime, or your favorite one. Copy and Paste below JSON data in Text Editor or create your own base on the What is JSON article. Once file data are validated, save the file with the extension of . json, and now you know how to create the Valid JSON document.

How do I export a JSON object?

It is easy to export the JSON object to a JSON file by using JSON. stringify method.


1 Answers

You can use 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] "[\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 
like image 138
jdharrison Avatar answered Oct 09 '22 02:10

jdharrison