R Read JSON Files

JSON (JavaScript Object Notation) is the dominant format for web APIs and modern data exchange. It stores data as nested key-value pairs and arrays. R does not read JSON natively, but the jsonlite package makes it simple — one function reads JSON into a data frame or list.

What JSON Looks Like

students.json:
[
  {"name": "Anita", "age": 22, "score": 88, "city": "Delhi"},
  {"name": "Ravi",  "age": 25, "score": 72, "city": "Mumbai"},
  {"name": "Seema", "age": 21, "score": 45, "city": "Chennai"}
]

Square brackets [ ] denote an array (list of items). Curly brackets { } denote an object (key-value pairs).

Installing and Loading jsonlite

install.packages("jsonlite")
library(jsonlite)

Reading JSON from a File

students <- fromJSON("students.json")
print(students)
#    name age score    city
# 1 Anita  22    88   Delhi
# 2  Ravi  25    72  Mumbai
# 3 Seema  21    45 Chennai

class(students)   # "data.frame"  (auto-converted from JSON array)

Reading JSON from a Web API

# Public API example: exchange rates
url <- "https://api.exchangerate-api.com/v4/latest/USD"
data <- fromJSON(url)

data$base         # "USD"
data$date         # "2024-08-15"
data$rates$INR    # 83.5 (USD to INR rate)

Nested JSON Structures

# Nested JSON:
# {
#   "company": "TechCorp",
#   "employees": [
#     {"name": "Alice", "dept": "Engineering"},
#     {"name": "Bob",   "dept": "Marketing"}
#   ]
# }

company <- fromJSON("company.json")
company$company                  # "TechCorp"
company$employees                # data frame of employees
company$employees$name           # "Alice" "Bob"

Converting R Data to JSON

# Data frame to JSON
df <- data.frame(name=c("X","Y"), value=c(10,20))
toJSON(df, pretty=TRUE)
# [
#   {"name": "X", "value": 10},
#   {"name": "Y", "value": 20}
# ]

# List to JSON
my_list <- list(name="Alice", scores=c(85,90,78))
toJSON(my_list, pretty=TRUE, auto_unbox=TRUE)

Writing JSON to a File

result <- data.frame(
  product = c("A","B","C"),
  sales   = c(1200, 850, 1600)
)

write_json(result, "sales_result.json", pretty=TRUE)

Flattening Deeply Nested JSON

# When API returns complex nesting, use flatten=TRUE
api_data <- fromJSON("complex_api.json", flatten=TRUE)

# Or manually navigate nesting
data <- fromJSON("nested.json")
flat_df <- do.call(rbind, lapply(data$items, as.data.frame))

Practical: Fetch and Analyze API Data

library(jsonlite)

# Get public GitHub user info
url  <- "https://api.github.com/users/hadley"
user <- fromJSON(url)

cat("Name:       ", user$name, "\n")
cat("Public repos:", user$public_repos, "\n")
cat("Followers:  ", user$followers, "\n")

JSON is the language of the web. Every API you ever call — weather services, financial data providers, social media platforms, government open data — returns JSON. Learning to read and parse JSON with jsonlite opens R to the entire world of live internet data.

Leave a Comment

Your email address will not be published. Required fields are marked *