JavaScript Object Notation (JSON) stores text-based data in a human-readable format. It helps to transfer data between multiple web applications, from server side to client for display, etc., and vice versa.
To deal with JSON files in R
language, the rjson
package is required. You can install the rjson
package through the following command:
install.packages("rjson")
The rjson
library helps perform multiple tasks, like:
To read a JSON file, you can use the fromJSON()
method of the rjson
library.
In the code snippet below, we have two files named main.r
and data.json
. main.r
contains code to read the data.json
file using the fromJSON()
method.
# Load the package required to read JSON files.install.packages("rjson") # Optionallibrary("rjson")# Give the input file name to the function.myData <- fromJSON(file="data.json")# Print the result.print(myData)
To convert a JSON file to a dataframe, you can use the as.data.frame()
method.
We simply use the fromJSON()
function to read data from the data.json
file and pass loaded data to the as.data.frame()
method to convert into a data frame.
In the code snippet below, we have two files named main.r
and data.json
. main.r
contains code to read the data.json
file to the myData
variable. as.data.frame(myData)
helps to convert raw JSON data into a data frame.
# Load the package# required to read JSON files.library("rjson")# Passing argument filesmyData <- fromJSON(file="data.json")# Convert JSON file to dataframe.json_data_frame <- as.data.frame(myData)print(json_data_frame)