Parsing JSON with jsonlite
Convert JSON strings to R lists and data frames with fromJSON().
Parsing JSON with jsonlite is a free R Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.
What Is JSON?
JSON (JavaScript Object Notation) is the universal data interchange format for APIs and web services. R's jsonlite package converts JSON to R objects (lists, data frames) and back, following tidy conventions.
library(jsonlite)
# JSON looks like:
# { "name": "Alice", "age": 30, "active": true }
# fromJSON parses JSON string to R object
json_str <- '{"name":"Alice","age":30,"active":true}'
result <- fromJSON(json_str)
class(result) # 'list'
result$name # 'Alice'
result$age # 30 (numeric)
result$active # TRUE (logical)fromJSON(): Basic Parsing
fromJSON(txt) parses a JSON string, URL, or file path. It automatically converts JSON types: strings → character, numbers → numeric, booleans → logical, null → NA, arrays → vectors, objects → named lists.
library(jsonlite)
# Parsing different JSON types
fromJSON('"hello"') # character: 'hello'
fromJSON('42') # numeric: 42
fromJSON('true') # logical: TRUE
fromJSON('null') # NA
fromJSON('[1, 2, 3]') # numeric vector: c(1,2,3)
fromJSON('["a", "b", "c"]') # character vector
# Nested object
json <- '{"x": 1, "y": [2, 3], "z": null}'
obj <- fromJSON(json)
obj$x # 1
obj$y # c(2, 3)
obj$z # NAtoJSON(): Serializing R to JSON
toJSON(x) converts R objects to JSON strings. Use auto_unbox=TRUE to convert length-1 vectors to JSON scalars (not arrays). pretty=TRUE adds indentation for readability.
library(jsonlite)
# Basic serialization
toJSON(c(1, 2, 3)) # '[1,2,3]'
toJSON(list(a=1, b='two')) # '{"a":[1],"b":["two"]}'
# auto_unbox: length-1 vectors become scalars
toJSON(list(name='Bob', age=25), auto_unbox = TRUE)
# '{"name":"Bob","age":25}'
# pretty printing
cat(toJSON(list(x=1, y=c(2,3)), pretty = TRUE))
# {
# "x": [1],
# "y": [2, 3]
# }JSON Arrays to Data Frames
JSON arrays of objects automatically convert to data frames with fromJSON(). This is one of jsonlite's most useful features — API responses are often arrays of records, perfectly suited for data frames.
library(jsonlite)
# JSON array of objects -> data frame
json_array <- '[
{"name": "Alice", "age": 30, "score": 95},
{"name": "Bob", "age": 25, "score": 87},
{"name": "Carol", "age": 35, "score": 92}
]'
df <- fromJSON(json_array)
class(df) # 'data.frame'
nrow(df) # 3
print(df)
# name age score
# Alice 30 95
# Bob 25 87
# Carol 35 92Data Frame to JSON
Converting a data frame to JSON with toJSON(df) produces a JSON array of objects (one per row). This is the standard format for sending tabular data to web APIs.
library(jsonlite)
df <- data.frame(
product = c('Apple', 'Banana', 'Cherry'),
price = c(1.20, 0.50, 3.00),
in_stock = c(TRUE, TRUE, FALSE),
stringsAsFactors = FALSE
)
# Default: each value is an array (even scalars)
cat(toJSON(df, pretty = FALSE))
# auto_unbox: single values become JSON scalars
cat('\n---\n')
cat(toJSON(df, auto_unbox = TRUE, pretty = TRUE))fromJSON() from a URL
fromJSON(url) can directly fetch and parse JSON from a URL. This is the simplest way to call a public JSON API that doesn't require authentication.
library(jsonlite)
# Read JSON directly from a URL (requires internet)
# Example: JSONPlaceholder (free test API)
# result <- fromJSON('https://jsonplaceholder.typicode.com/todos/1')
# result$title # todo title
# result$completed # TRUE/FALSE
# Example: GitHub API
# repos <- fromJSON('https://api.github.com/users/hadley/repos')
# repos$name # vector of repo names
# nrow(repos) # number of repos returned
# Simulate with local JSON string:
result <- fromJSON('{"id":1,"title":"Learn R","completed":false}')
cat('Task:', result$title, '\nDone:', result$completed)prettify() and minify()
prettify(json_string) adds indentation and newlines for human readability. minify(json_string) removes whitespace for compact transmission. Both operate on raw JSON strings.
library(jsonlite)
# Compact (minified) JSON
compact_json <- '{"name":"Alice","scores":[95,87,92],"active":true}'
cat('Minified:\n', compact_json, '\n\n')
# Prettify: add whitespace
cat('Prettified:\n')
cat(prettify(compact_json))
# {
# "name": "Alice",
# "scores": [95, 87, 92],
# "active": true
# }
# Minify: remove whitespace
pretty_json <- prettify(compact_json)
cat('\nRe-minified:\n')
cat(minify(pretty_json))flatten=TRUE for Nested Objects
When JSON has nested objects, fromJSON(json, flatten=TRUE) flattens nested keys into dotted column names, making it easier to work with as a data frame without manual unnesting.
library(jsonlite)
json <- '[
{"id": 1, "user": {"name": "Alice", "city": "NY"}},
{"id": 2, "user": {"name": "Bob", "city": "LA"}}
]'
# Without flatten: nested list column
df_nested <- fromJSON(json)
class(df_nested$user) # data.frame (nested!)
# With flatten: flat column names
df_flat <- fromJSON(json, flatten = TRUE)
names(df_flat) # c('id', 'user.name', 'user.city')
print(df_flat)
# id user.name user.city
# 1 Alice NY
# 2 Bob LAHandling JSON with NA and Missing Keys
JSON null maps to R's NA. Missing keys in JSON arrays (when one record has a field another lacks) are filled with NA in the resulting data frame.
library(jsonlite)
# JSON with null values
json_nulls <- '{"a": 1, "b": null, "c": "hello"}'
obj <- fromJSON(json_nulls)
obj$b # NA
is.na(obj$b) # TRUE
# Array with missing keys
json_missing <- '[
{"name": "Alice", "age": 30, "email": "a@b.com"},
{"name": "Bob", "age": 25}
]'
# 'email' missing from second record
df <- fromJSON(json_missing)
print(df)
# name age email
# Alice 30 a@b.com
# Bob 25 <NA>Writing JSON to Files
Use write_json() (or writeLines(toJSON(x), file)) to save R objects as JSON files. This is the standard output format for sharing data with web applications or APIs.
library(jsonlite)
results <- list(
model = 'linear_regression',
coefficients = list(intercept = 2.5, slope = 1.3),
r_squared = 0.87,
n_obs = 100
)
# Convert to JSON string
json_output <- toJSON(results, auto_unbox = TRUE, pretty = TRUE)
cat(json_output)
# Save to file (uncomment):
# write_json(results, 'model_results.json',
# auto_unbox = TRUE, pretty = TRUE)
# Or equivalently:
# writeLines(json_output, 'model_results.json')Validating JSON
validate(json_string) from jsonlite checks if a string is valid JSON, returning TRUE/FALSE. Useful before parsing, especially when handling user input or API responses that might be malformed.
library(jsonlite)
# Valid JSON
validate('{"name": "Alice", "age": 30}') # TRUE
validate('[1, 2, 3]') # TRUE
validate('"just a string"') # TRUE
# Invalid JSON
validate('{name: Alice}') # FALSE (unquoted keys)
validate('[1, 2, 3,]') # FALSE (trailing comma)
validate('') # FALSE
# Safe parsing pattern
safe_parse <- function(json) {
if (!validate(json)) {
warning('Invalid JSON')
return(NULL)
}
fromJSON(json)
}
safe_parse('{"x": 1}')
safe_parse('{bad json}')Quick Check
Test your knowledge of JSON parsing with jsonlite in R.
Recap: JSON with jsonlite
Key takeaways: fromJSON() parses JSON strings, URLs, and files into R lists or data frames. toJSON() converts R to JSON — use auto_unbox=TRUE for scalars. prettify()/minify() format strings. flatten=TRUE flattens nested objects. JSON null becomes NA. validate() checks JSON validity before parsing.
library(jsonlite)
# Complete jsonlite workflow:
# Parse
df <- fromJSON('[{"a":1,"b":2},{"a":3,"b":4}]')
print(df)
# Serialize
json <- toJSON(df, auto_unbox = TRUE, pretty = FALSE)
cat(json, '\n')
# Flatten nested
nested <- fromJSON(
'[{"id":1,"x":{"val":10}},{"id":2,"x":{"val":20}}]',
flatten = TRUE
)
print(nested)
# Validate before parse
validate('{"key": "value"}') # TRUELearn R with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 43
- Lessons
- 159
Frequently Asked Questions
Is the “Parsing JSON with jsonlite” lesson free?
Yes — any 3 lessons of the R Academy learning path, including “Parsing JSON with jsonlite”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.
What will I learn in “Parsing JSON with jsonlite”?
Convert JSON strings to R lists and data frames with fromJSON(). You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
How long does the “Parsing JSON with jsonlite” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Parsing JSON with jsonlite
- Making HTTP Requests with httr2
- Consuming REST APIs in R
- Handling Nested JSON Structures