Handling Nested JSON Structures
Flatten deeply nested JSON into tidy data frames for analysis.
Why Nested JSON Is Tricky
REST APIs often return deeply nested JSON where a single field may contain an array of objects, which in turn contain more objects. Flattening this structure into a tidy data frame requires understanding how jsonlite, purrr, and tidyr work together.
# Example nested JSON from a REST API:
json_str <- '{
"user": {
"id": 1,
"name": "Alice",
"orders": [
{"order_id": 101, "total": 59.99, "status": "shipped"},
{"order_id": 102, "total": 24.50, "status": "pending"}
]
}
}'
# The challenge: 'orders' is an array of objects inside 'user'
cat('Nested JSON loaded as string, length:', nchar(json_str))fromJSON() — Basic Parsing
jsonlite::fromJSON() converts a JSON string or file path into R objects. Simple flat JSON becomes a list or data frame. Nested JSON becomes a nested list — arrays of objects become data frames stored inside list columns.
library(jsonlite)
# Parse flat JSON
flat_json <- '{"name": "Alice", "age": 30, "score": 95.5}'
result <- fromJSON(flat_json)
cat('Name:', result$name, '\n')
cat('Age: ', result$age, '\n')
# Parse an array of objects — becomes a data frame
array_json <- '[{"id":1,"val":10},{"id":2,"val":20},{"id":3,"val":30}]'
df <- fromJSON(array_json)
cat('Class:', class(df), '\n')
print(df)All lessons in this course
- Parsing JSON with jsonlite
- Making HTTP Requests with httr2
- Consuming REST APIs in R
- Handling Nested JSON Structures