Skip to content
Related Articles

Related Articles

How to read JSON files in R

Improve Article
Save Article
  • Last Updated : 23 Sep, 2022
Improve Article
Save Article

In this article, we will see How to read a JSON file in R through an example, and also we will have a look at how to convert JSON data into a dataframe. As we know, in the R language, we have to install different packages to deal with other things, so the first step is nothing but installing the package rjson.

Stepwise Implementation:

Step 1: To read a file in R language, we must install a package called rjson.So to install on the package, we will use a function called install.packages().

R




install.packages("rjson",  dependencies = T)


Output:

 

Step 2: In this step, we need to load or store the package, and for that, we can use the native function library. It loads the rjson package or stores the rjson package for further use. Below code in R language is used to store the rjson package.

R




library(rjson)


We can see that the library is loaded successfully

Step 3: In this step, we need to create a data file, or JSON file in this example, we are using the below datafile. The important thing about the data file is the extension of the file must be .json

  “CollegeID”:[“1″,”2″,”3″,”4″,”5″,”6″,”7″,”8” ],

  “Name”:[“Priyanshu”,”Yashodhra”,”Abhishek”,”Tanmay”,”Samriddha”,”Anjali”,”Samrat”,”Nikhil” ],

  “SubjectCode”:[“123″,”67″,”62″,”77″,”81″,”56″,”92″,”22” ],

  

  “CourseStartDate”:[ “02/08/2018″,”09/03/2018″,”08/05/2018″,”05/11/2019″,”03/06/2019″,”05/11/2019”,

     “07/10/2020″,”06/07/2015”],

  “StudentDepartment”:[ “IT”,”Computer”,”ENTC”,”Electronics”,”Electrical”,”Civil”,”Chemical”,”Mechanical”]

}

Step 4: Now, in this step, we have to read the file that has JSON formatted data, and for that, we will use a function called fromJSON(). rjson provides this function which reads the file with JSON formatted data.

Syntax : fromJSON(path_of_a_file)

The below code in the R language is helpful for the fromJSON() function. Link to the json file link.

R




JsonData <- fromJSON(file = 'C:/Users/PRIYANSHU\
GUPTA/Desktop/student.json')
print(JsonData)


Output:

 

Step 5: Now, in this step, we will see how to convert JSON data into a dataframe, and for this, we will use a function called as.data.frame(). This function helps us to convert JSON data into a dataframe.

Syntax : as.data.frame(json_data)

R




jsonData_to_DataFrame <- as.data.frame(JsonData)


Output:

 

Step 6: Now you can see that the new object is being named ‘jsonData_to_Data…’

 

Step 7: In this, we need to click on that to see that our data is in tabular form with rows and columns.

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!