JSON Files in R

To get JSON files into R, you first need to install or load the rjson package. Once you have installed and loaded this, you can use the fromJSON() function to read the json file.

Install the rjson Package:

install.packages("rjson")
# Load the package required to read JSON files.
library("rjson")

Read the a JSON File:

Download a sample JSON file from here. And save the file with a .json extension and  choosing the file type as all files(*.*). Then load it using the following code.

Download the the sample JSON 

 

mydata <- fromJSON(file="https://makemeanalyst.com/wp-content/uploads/2017/06/sample_json.txt")
mydata

Output:

> mydata
$`Emp Id`
[1] "1" "2" "3" "4" "5"

$Name
[1] "Mr. X" "Mr. Y" "Mr. Z" "Mr. K" "Mr. S"

$Dept
[1] “Analytics” “Cloud Wings” “Big Data Analytics” “Identity Management” “HR”

Convert the JSON to a Data Frame:

You can easily convert JSON to a Data Frame using following code.

data<- data.frame(mydata)
data

Output:

Emp.Id Name Dept
1 1 Mr. X Analytics
2 2 Mr. Y Cloud Wings
3 3 Mr. Z Big Data Analytics
4 4 Mr. K Identity Management
5 5 Mr. S HR

jsonlite is another very good package in R for working with JSON data. Check the documentation for jsonlite by clicking here.

Matrices, Lists, Factors

Control Structures