Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

json
communitycreator
r

How to read JSON files in R

Salman Yousaf

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:

  • Reading JSON files.
  • Converting JSON into a dataframe or table.

Reading JSON files

To read a JSON file, you can use the fromJSON() method of the rjson library.

Code

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.

main.r
data.json
# Load the package required to read JSON files.
install.packages("rjson") # Optional
library("rjson")
# Give the input file name to the function.
myData <- fromJSON(file="data.json")
# Print the result.
print(myData)
Expected output

Convert JSON into a dataframe

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.

Code

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.

main.r
data.json
# Load the package 
# required to read JSON files.
library("rjson")
# Passing argument files
myData <- fromJSON(file="data.json")
# Convert JSON file to dataframe.
json_data_frame <- as.data.frame(myData)
print(json_data_frame)
Expected Output

RELATED TAGS

json
communitycreator
r
RELATED COURSES

View all Courses

Keep Exploring