# Reading and Writing JSON files in R

A JSON file store simple data structures and objects in JavaScript object Notation (JSON) format. JSON is a standard data lightweight interchange format that is primarily used for transmitting data between a web application and a server. The JSON file is a text file that is language independent, self-describing, and easy to understand. Here we will discuss reading and writing JSON files in R Language in detail using the R package “rjson“.

Since JSON file format is text only, which can be sent to and from a server, and used as a data format by any programming language. The data in the JSON file is nested and hierarchical. Let us start reading and writing JSON files in R.

## Reading JSON files in R

R can read JSON files using the rjson package. First, install rjson package.

Issue the following command in the R console, to install the rjson package.

install.packages("rjson")

Let create a JSON file. Copy the following lines into a text editor such as notepad. Save the file with a .json extension and choosing the file type as all files(*.*). Let the file name is “data.json”, stored on “D:” drive.

{
"ID":["1","2","3","4","5","6","7","8" ],
"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
"Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],

"StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
"7/30/2013","6/17/2014"],
"Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"]
}

To read a JSON file, the rjson package needs to be loaded. Use fromJSON( ) function to read the file.

# Give the data file name to the function.
result <- fromJSON(file = "D:\\data.json")
# Print the result.
print(result)

The JSON file now can be converted to a Data Frame for further analysis using the as.data.frame() function.

# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(result)
print(json_data_frame)

## Writing JSON objects to .Json file

To write JSON Object to file, the toJSON() function from the rjson library can be used to prepare a JSON object and then use the write() function for writing the JSON object to a local file.

Let create a list of objects as follows

list1 <- vector(mode="list", length=2)
list1[[1]] <- c("apple", "banana", "rose")
list1[[2]] <- c("fruit", "fruit", "flower")

read the above list to JSON

jsonData < toJSON(list1)

write JSON object to file

write(jsonData, "output.json")

Read more about importing and exporting data in R: see the post