R JSON File

JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data. JSON file is often used when data is sent from a server to a web page. It often stores data as text in human readable format. R can read JSON file using the rjson package.

Install rjson Package

To install rjson package use the following command:

install.packages("rjson")

Create a JSON File

Copy the following code into notepad or any other text editor and save this file with a .json extension.

{
   "ID":["1","2","3","4","5" ],
   "Name":["Nikita","Deep","Aman","Nidhi","Sonu" ],
   "Salary":["50000","20000","25000","23000","30000" ],   
   "StartDate":[ "1/1/2018","9/23/2014","11/15/2017","5/11/2015","3/27/2019"],
   "Dept":[ "IT","Operations","IT","HR","Finance"]
}

Read the JSON File

fromJSON() function is used to read the JSON file in R. It is stored as a list in R.

Example:

# Load the package required package.
library("rjson")
result <- fromJSON(file = "Student.json")
# Print the result.
print(result)

Output:

$ID

[1] "1" "2" "3" "4" "5"

$Name

[1] "Nikita" "Deep"   "Aman"   "Nidhi"  "Sonu" 

$Salary

[1] "50000" "20000" "25000" "23000" "30000"

$StartDate

[1] "1/1/2018"   "9/23/2014"  "11/15/2017" "5/11/2015"  "3/27/2019"

$Dept

[1] "IT"         "Operations" "IT"         "HR"         "Finance"

Convert JSON to a Data Frame

We can convert the JSON data which is extracted from fromJson() function into the form of data frame. For this R provides a function i.e. as.data.frame() function.

Example:

# Load the package required to read JSON files.
library("rjson")
# Give the input file name to the function.
result <- fromJSON(file = "Student.json")
# Convert JSON file to a data frame.
df <- as.data.frame(result)
print(df)

Output:

  ID   Name Salary  StartDate       Dept
1  1 Nikita  50000   1/1/2018         IT
2  2   Deep  20000  9/23/2014 Operations
3  3   Aman  25000 11/15/2017         IT
4  4  Nidhi  23000  5/11/2015         HR
5  5   Sonu  30000  3/27/2019    Finance
Reference: https://stackoverflow.com/questions/2617600/importing-data-from-a-json-file-into-r