R JSON Files Handling

JSON stands for JavaScript Object Notation, is a lightweight data interchange format. It is primarily used to transmit data between a server and web application. For JSON file handling in R, we need to install the JSON packages.

Install JSON Package

R provides 'jsonlite' package for interacting with JSON. To install this package, use the install.package() command with the package name -

install.packages("jsonlite")

Load jsonlite package

We hope you have successfully installed the jsonlite package. Now to use this package in your application, you need to load the package library by using library() function.

library("jsonlite")




Reading JSON File

R provides fromJSON() function to read data from a JSON file. The syntax of fromJSON() is -

fromJSON("filename")

Here, filename is the name of json file with path, it does not need to mention the file path if the file exists in the current working directory.

Example

Suppose, there is a json file name 'employee.json' located in the current working directory.

[
	{
	 "Name": "Dhyan"
	 "Age": "26"
	 "Department": "HR"
	},
	{
	 "Name": "Jorz"
	 "Age": "27"
	 "Department": "Finance"
	},
	{
	 "Name": "Mary"
	 "Age": "29"
	 "Department": "IT"
	},
	{
	 "Name": "Sinoy"
	 "Age": "32"
	 "Department": "IT"
	}
]

The following command reads the above json file -

data <- fromJSON("employee.json")
print(data)
   Name Age Department
1 Dhyan  26         HR
2  Jorz  27    Finance
3  Mary  29         IT
4 Sinoy  32         IT




Writing Data to JSON File

R provides toJSON() function to write data to a JSON file. The syntax of toJSON() is -

toJSON(dataframe)

Example

Suppose we have the following data frame.

data <- data.frame(id = c(1:4), name = c("Mary", "Soy", "Alexa", "Roxy"), class = 5)

The following command converts the data frame to a json file -

> data <- data.frame(id = c(1:4), name = c("Mary", "Soy", "Alexa", "Roxy"), class = 5)
> jData <- toJSON(data, pretty=TRUE)
> jData
[
  {
    "id": 1,
    "name": "Mary",
    "class": 5
  },
  {
    "id": 2,
    "name": "Soy",
    "class": 5
  },
  {
    "id": 3,
    "name": "Alexa",
    "class": 5
  },
  {
    "id": 4,
    "name": "Roxy",
    "class": 5
  }
] 
>