Open In App

How to read JSON files in R

Last Updated : 29 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read for humans as well as machines to parse and generate. It's widely used for APIs, web services and data storage. A JSON structure looks like this:

{
"name": "John",
"age": 30,
"city": "New York"
}

JSON data can be organized in objects (key-value pairs) and arrays (ordered lists of values) making it flexible for various use cases. Reading and writing JSON in R allows you to easily integrate it with web APIs, process data from external sources or handle configuration files.

To read JSON data in R we’ll use the jsonlite package which provides simple functions for parsing JSON into R objects.

1. Installing and Loading jsonlite Package

To work with json files we must install the jsonlite package available in R.

R
install.packages("jsonlite")

Once installed, load the package:

R
library(jsonlite)

2. Read JSON Data from a File

To read a JSON file on our system we will use the fromJSON() function. This function parses the JSON file and returns a corresponding R object such as a list or data frame depending on the structure of the JSON data. We will be using the following JSON file for this article.

R
json_data <- fromJSON("/content/indian_addresses_sample_data.json")

3. Inspecting Data

We will use the str() function to display the structure of the data.

R
str(json_data)

Output:

o1
Inspecting Data

4. Accessing Data in JSON

After loading the JSON data we can access specific elements like we do in a data frame.

R
city <- json_data$address$city
print(city)

Output:

o2
City from the address

Here in the JSON data is more complex such as containing nested objects or arrays so we accessed them using additional indexing of city.

5. Converting JSON Data to a Data Frame

If the JSON data is structured in a tabular format we can convert it linto a dataframe using as.data.frame() function.

R
df <- as.data.frame(json_data)

Output:

o3
Converting JSON to Data Frame

With these methods we can easily work with JSON data in R and integrate it in our analysis workflow.


Next Article
Article Tags :

Similar Reads