How to read JSON files in R
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.
install.packages("jsonlite")
Once installed, load the package:
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.
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.
str(json_data)
Output:

4. Accessing Data in JSON
After loading the JSON data we can access specific elements like we do in a data frame.
city <- json_data$address$city
print(city)
Output:

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.
df <- as.data.frame(json_data)
Output:

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