Open In App

How to read this JSON file with jsonlite in R?

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JSON data is represented as key-value pairs, which are similar to the concept of a dictionary in Python or a list of named elements in R. In this article, we will learn how to access different components of a JSON file using R.

What is jsonlite package in R?

The jsonlite package in R provides an easy-to-use interface for reading and manipulating JSON data. It includes several functions that allow us to convert JSON data into R objects, such as lists and data frames. One of the main advantages of using the Jsonlite package is that it can handle both simple and complex JSON data structures.

Steps to read this JSON file in R

The following are the steps needed to access different components of a JSON file using R. You can download the dataset used from here.

Json Dataset Used: example_1.json, sample2.json

Step 1: Before we can start working with JSON data in R, we need to load the jsonlite package. This can be done using the library() function.

R




library(jsonlite)


Step 2: Read the JSON file.

R




data <- read_json("path/to/file.json")


Step 3: Convert the Json data to dataframe:

R




json_data_frame <- as.data.frame(data)


Example 1:

Here we are using example_1.json to convert the JSON file to a data frame.

R




# Load the jsonlite package
library(jsonlite)
  
# Read the JSON file
json_data <- fromJSON("example_1.json")
  
# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(json_data)
  
# Print the data
print(json_data_frame)


Output:

 

Example 2:

Here we are using sample2.json to convert the JSON file to a data frame.

R




# Load the jsonlite package
library(jsonlite)
  
# Read the JSON file
json_data <- fromJSON("sample2.json")
  
# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(json_data)
  
# Print the data
print(json_data_frame)


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads