R JSON
last modified November 20, 2026
JSON is a text format for objects, arrays, strings, numbers, booleans, and
null. It is the usual shape of a web API response and a common way to store
configuration and event data. The jsonlite package converts
between JSON and R objects: fromJSON parses text into lists,
vectors, or data frames, and toJSON serialises an R object back to
text. This article covers both directions, the simplification rules that turn
nested JSON into data frames, missing values, live data from public web APIs,
JSON Lines, files, and a complete example that combines two API endpoints. The
examples use jsonlite 2.0.0 and R 4.5.2.
The examples need the jsonlite package, which is not part of base R. Install it
once with install.packages("jsonlite"); the
installing packages section of the
introduction explains the details.
From R objects to JSON
A named list becomes a JSON object, and an unnamed list or vector becomes a
JSON array. By default, toJSON writes every scalar as a
one-element array, because R vectors can have any length. auto_unbox =
TRUE writes a length-one vector as a plain scalar, which is usually what
an API expects. The result is a character string of class json,
and fromJSON turns it back into an R list.
library(jsonlite)
person <- list(name = "Ada", age = 36, active = TRUE)
json <- toJSON(person, auto_unbox = TRUE)
cat(json, "\n")
cat("class:", class(json), "\n")
back <- fromJSON(json)
cat("name:", back$name, "\n")
cat("age:", back$age, "\n")
cat("active:", back$active, "\n")
The three fields become an object with three members, and the scalar values
lose the brackets that auto_unbox = FALSE would add. The class
json marks the string as serialised JSON for printing and for
functions that accept JSON input. fromJSON returns a list with the
same names, and the boolean true comes back as the logical
TRUE. The numbers and strings keep their R types.
$ Rscript basics.R
{"name":"Ada","age":36,"active":true}
class: json
name: Ada
age: 36
active: TRUE
Data frames
A data frame is serialised as a JSON array of objects, one object per row, with
the column names as the member names. This row-oriented form is what most APIs
produce, and it is the form that fromJSON turns back into a data
frame when every element has the same fields. pretty = TRUE adds
indentation and line breaks, which makes the text readable during development.
library(jsonlite)
scores <- data.frame(name = c("Ada", "Grace"), score = c(91, 88))
json <- toJSON(scores, pretty = TRUE)
cat(json, "\n")
back <- fromJSON(json)
print(back)
cat("class:", class(back)[1], "\n")
The array has two objects, each with a name and a
score. fromJSON recognises the repeated fields and
returns a data frame with the original column names and types.
pretty = TRUE changes only the whitespace, not the data. A data
frame with a list column is the exception: the column cannot be represented as
a simple JSON scalar, so each element becomes a nested array or object.
$ Rscript dataframes.R
[
{
"name": "Ada",
"score": 91
},
{
"name": "Grace",
"score": 88
}
]
name score
1 Ada 91
2 Grace 88
class: data.frame
Nested objects
Real JSON rarely has a flat shape. An object can contain an array of objects,
and an object inside that array can contain another array. With the default
simplifyVector = TRUE, fromJSON turns an array of
records into a data frame and leaves a column whose values are themselves
arrays as a list column. With simplifyVector = FALSE, every
object stays a list and every array stays a list, which preserves the exact
shape at the cost of more code to reach the values.
library(jsonlite)
text <- '{
"team": "analytics",
"members": [
{"name": "Ada", "skills": ["R", "SQL"]},
{"name": "Grace", "skills": ["Python", "R"]}
]
}'
parsed <- fromJSON(text)
str(parsed)
cat("team:", parsed$team, "\n")
cat("names:", parsed$members$name, "\n")
cat("first skill:", parsed$members$skills[[1]][1], "\n")
flat <- fromJSON(text, simplifyVector = FALSE)
cat("members class:", class(flat$members)[1], "\n")
cat("member count:", length(flat$members), "\n")
The simplified result is a list with a character team and a data
frame members. The skills column is a list column:
each row holds a character vector, so parsed$members$skills[[1]][1]
returns "R". The unsimplified result keeps members as
a list of two lists, which is the safer shape when the records have different
fields or when the order of the fields matters. The str call shows
the chosen shape before any extraction code is written.
$ Rscript nested.R List of 2 $ team : chr "analytics" $ members:'data.frame': 2 obs. of 2 variables: ..$ name : chr [1:2] "Ada" "Grace" ..$ skills:List of 2 .. ..$ : chr [1:2] "R" "SQL" .. ..$ : chr [1:2] "Python" "R" team: analytics names: Ada Grace first skill: R members class: list member count: 2
Flattening records
A data frame with a data-frame column is awkward to use in a model or a CSV
file. The flatten argument of fromJSON joins the
nested column names with a dot, so a user column with
name and city becomes user.name and
user.city. The result is a flat data frame with one row per
record, ready for write.csv or a regression formula.
library(jsonlite)
text <- '[
{"id": 7, "user": {"name": "Ada", "city": "Bratislava"}},
{"id": 8, "user": {"name": "Bob", "city": "Kosice"}}
]'
nested <- fromJSON(text)
str(nested)
flat <- fromJSON(text, flatten = TRUE)
print(flat)
cat("columns:", names(flat), "\n")
Without flattening, the user column is a data frame with two
columns, and the printed result shows only the top level. With
flatten = TRUE, the two fields move into the top-level frame and
the column names record their origin. The identifier and the two user fields
form one row per record. Flattening is a convenience, not a lossless
transformation: nested arrays that do not have a one-to-one row structure still
need a list column or a separate table.
$ Rscript flatten-records.R 'data.frame': 2 obs. of 2 variables: $ id : int 7 8 $ user:'data.frame': 2 obs. of 2 variables: ..$ name: chr "Ada" "Bob" ..$ city: chr "Bratislava" "Kosice" id user.name user.city 1 7 Ada Bratislava 2 8 Bob Kosice columns: id user.name user.city
Missing values and null
JSON has one missing-value marker, null, while R has
NA for typed vectors and NULL for absent objects.
toJSON writes NA as null when the
na argument is set to "null", and
fromJSON turns null back into NA in a
data frame column. A null in an object that becomes a list is
returned as NULL, so the two representations are not
interchangeable in every context.
library(jsonlite)
values <- data.frame(id = 1:3, score = c(90, NA, 75))
json <- toJSON(values, na = "null", pretty = TRUE)
cat(json, "\n")
back <- fromJSON(json)
print(back)
cat("missing:", sum(is.na(back$score)), "\n")
The second record has a null score in the JSON text. The explicit
na = "null" makes jsonlite keep the field and write it as
null; without that argument, the data frame method drops the field
from the row, which a reader may interpret as absent rather than null. Reading
the array back produces a data frame with an NA in that cell, so
the count of missing values is one. The other two scores keep their numbers.
Being explicit documents the choice and avoids surprises when the JSON is
consumed by a system that treats a missing field differently from a null field.
$ Rscript nulls.R
[
{
"id": 1,
"score": 90
},
{
"id": 2,
"score": null
},
{
"id": 3,
"score": 75
}
]
id score
1 1 90
2 2 NA
3 3 75
missing: 1
Reading JSON from a URL
fromJSON accepts a URL as well as a string. It downloads the
response and parses it in one step, so a public web API that needs no key can
be read without any other package. The GitHub REST API describes a repository
as a single JSON object, which fromJSON returns as a named list.
Unauthenticated clients may make 60 requests per hour, which is plenty for
these examples.
library(jsonlite)
url <- "https://api.github.com/repos/jeroen/jsonlite"
repo <- fromJSON(url)
cat("fields:", length(repo), "\n")
cat("name:", repo$full_name, "\n")
cat("description:", repo$description, "\n")
cat("language:", repo$language, "\n")
cat("license:", repo$license$name, "\n")
cat("created:", format(as.Date(repo$created_at)), "\n")
cat("stars:", repo$stargazers_count, "\n")
The response has 84 fields, and the script prints a few of them. The
license member is a nested object, so its name is reached with a
second $. The created_at timestamp is an ISO 8601
string, and as.Date keeps its date part. The star count is live
data and changes over time; the other fields are stable.
$ Rscript github-repo.R fields: 84 name: jeroen/jsonlite description: Simple JSON Parser and Generator for R language: C license: Other created: 2013-10-03 stars: 405
Flattening an API response
JSONPlaceholder is a free fake REST API for testing and teaching. Its data
never changes, so the output below is what every reader gets. The
/users endpoint returns an array of ten users, each with nested
address and company objects, and
address contains a further geo object. With
flatten = TRUE, the whole response becomes one flat data frame.
library(jsonlite)
url <- "https://jsonplaceholder.typicode.com/users"
users <- fromJSON(url, flatten = TRUE)
cat("rows:", nrow(users), "columns:", ncol(users), "\n")
cat("nested:", grep("\\.", names(users), value = TRUE)[1:4], "\n")
contacts <- users[, c("name", "address.city", "company.name")]
print(head(contacts, 4))
The eight top-level fields grow to fifteen columns once the nested objects are
spread out. The grep call lists the first four column names that
contain a dot, all of which come from address. Selecting three
columns by name gives a small contact table, with the city and the company
name taken from two different nested objects.
$ Rscript users.R
rows: 10 columns: 15
nested: address.street address.suite address.city address.zipcode
name address.city company.name
1 Leanne Graham Gwenborough Romaguera-Crona
2 Ervin Howell Wisokyburgh Deckow-Crist
3 Clementine Bauch McKenziehaven Romaguera-Jacobson
4 Patricia Lebsack South Elvis Robel-Corkery
Arrays with nested values
Many APIs return an array of records with a query string that controls the
result. The GitHub releases endpoint accepts per_page, which
limits the response to the five newest ggplot2 releases. Each release has an
author object and an assets array. The default
simplification turns the author into a data-frame column and the assets into
a list column, just like the inline examples above.
library(jsonlite)
url <- "https://api.github.com/repos/tidyverse/ggplot2/releases?per_page=5"
releases <- fromJSON(url)
cat("class:", class(releases), "\n")
cat("author class:", class(releases$author), "\n")
cat("assets class:", class(releases$assets), "\n")
summary <- data.frame(tag = releases$tag_name,
date = as.Date(releases$published_at),
author = releases$author$login)
print(summary)
The three class lines confirm the shapes before the code relies
on them. releases$author$login reads a column of the nested data
frame, and as.Date shortens the publication timestamps. The
summary has one row per release. The list changes whenever a new version of
ggplot2 is released.
$ Rscript releases.R
class: data.frame
author class: data.frame
assets class: list
tag date author
1 v4.0.4 2026-11-16 teunbrand
2 v4.0.3 2026-04-22 thomasp85
3 v4.0.2 2026-02-03 thomasp85
4 v4.0.1 2025-11-14 thomasp85
5 v4.0.0 2025-09-11 thomasp85
JSON Lines
JSON Lines, also called newline-delimited JSON, stores one JSON value per line
instead of one large array. The format is common in logs and streaming
exports, because a reader can process a line without parsing the whole file.
jsonlite writes the format with stream_out and reads it with
stream_in. Both work on a connection, such as one created with
file, and they process the records in pages, so a large file
does not have to fit in memory as text.
library(jsonlite)
events <- data.frame(id = 1:3, level = c("info", "warn", "info"),
value = c(10, 20, 30))
stream_out(events, file("events.ndjson"), verbose = FALSE)
cat(readLines("events.ndjson"), sep = "\n")
back <- stream_in(file("events.ndjson"), verbose = FALSE)
print(back)
cat("total:", sum(back$value), "\n")
unlink("events.ndjson")
stream_out writes one compact object per row of the data frame,
and readLines shows the three lines in the file.
stream_in parses them and combines the records into a data frame
with the original columns. verbose = FALSE turns off the progress
messages that both functions print by default. The total of the
value column is sixty.
$ Rscript json-lines.R
{"id":1,"level":"info","value":10}
{"id":2,"level":"warn","value":20}
{"id":3,"level":"info","value":30}
id level value
1 1 info 10
2 2 warn 20
3 3 info 30
total: 60
Reading and writing files
write_json writes a character string produced by
toJSON to a file, and read_json reads a file and
passes its contents to fromJSON. They are thin wrappers, but they
handle the connection and the encoding, which keeps file code short. The
pretty argument applies to the written text in the same way as it
does to toJSON.
library(jsonlite)
records <- data.frame(id = 1:3, value = c(10, 20, 30))
write_json(records, "records.json", pretty = TRUE)
cat("lines:", length(readLines("records.json")), "\n")
back <- read_json("records.json", simplifyVector = TRUE)
print(back)
cat("rows:", nrow(back), "\n")
unlink("records.json")
The pretty-printed file has fourteen lines for three records, because every
brace and field sits on its own line. read_json returns the same
data frame that fromJSON would produce from the string, with three
rows and the original values. The script removes the file after the check.
Without pretty, the same data would be one long line, which is
smaller but harder to inspect by eye.
$ Rscript files.R lines: 14 id value 1 1 10 2 2 20 3 3 30 rows: 3
Totals from list columns
This example parses an array of orders. Each order has an identifier, a
customer, and an array of items with a price and a quantity. The default
simplification turns the items into a list column of small data frames, so the
total for an order is a vapply over that column. The result is a
flat data frame with one row per order, and the script writes it back as JSON.
library(jsonlite)
text <- '[
{"id": 1, "customer": "Ada",
"items": [{"price": 10, "qty": 2}, {"price": 5, "qty": 1}]},
{"id": 2, "customer": "Bob",
"items": [{"price": 7, "qty": 3}]}
]'
orders <- fromJSON(text)
print(orders)
orders$total <- vapply(orders$items,
function(items) sum(items$price * items$qty),
numeric(1))
result <- data.frame(id = orders$id,
customer = orders$customer,
total = orders$total)
print(result)
cat("grand total:", sum(result$total), "\n")
cat(toJSON(result, pretty = TRUE), "\n")
Ada's order has two items, 10 times 2 plus 5 times 1, for a total of 25.
Bob's order has one item, 7 times 3, for a total of 21. The grand total is 46.
The vapply call returns a numeric vector with one element per
order, and the template numeric(1) makes the function fail if an
item sum is not a single number. The final toJSON writes the
three-column summary as an array of objects, which is the form an API would
accept.
$ Rscript orders.R
id customer items
1 1 Ada 10, 5, 2, 1
2 2 Bob 7, 3
id customer total
1 1 Ada 25
2 2 Bob 21
grand total: 46
[
{
"id": 1,
"customer": "Ada",
"total": 25
},
{
"id": 2,
"customer": "Bob",
"total": 21
}
]
A complete example
The final example combines two live endpoints of JSONPlaceholder. The
/todos endpoint returns 200 tasks, each with a
userId and a logical completed field, and
/users supplies the names and cities. The script counts the
finished tasks per user, joins the names with match, and writes
the two most productive users back as JSON.
library(jsonlite)
base <- "https://jsonplaceholder.typicode.com"
users <- fromJSON(paste0(base, "/users"))
todos <- fromJSON(paste0(base, "/todos"))
cat("users:", nrow(users), "todos:", nrow(todos), "\n")
done <- tapply(todos$completed, todos$userId, sum)
report <- data.frame(id = as.integer(names(done)), done = as.vector(done))
report$name <- users$name[match(report$id, users$id)]
report$city <- users$address$city[match(report$id, users$id)]
report <- report[order(-report$done, report$name), ]
print(head(report, 4), row.names = FALSE)
cat("overall:", sum(report$done), "of", nrow(todos), "done\n")
cat(toJSON(head(report, 2), pretty = TRUE), "\n")
tapply sums the logical completed column within
each user, because TRUE counts as one. The names of its result
are the user identifiers, which become the id column.
match finds the row of each identifier in users,
and the city comes from the nested address data frame. The
report is sorted by the count and then by name, so the two users with twelve
finished tasks appear in a fixed order. Ninety of the 200 tasks are done.
$ Rscript todos.R
users: 10 todos: 200
id done name city
5 12 Chelsey Dietrich Roscoeview
10 12 Clementina DuBuque Lebsackbury
1 11 Leanne Graham Gwenborough
8 11 Nicholas Runolfsdottir V Aliyaview
overall: 90 of 200 done
[
{
"id": 5,
"done": 12,
"name": "Chelsey Dietrich",
"city": "Roscoeview"
},
{
"id": 10,
"done": 12,
"name": "Clementina DuBuque",
"city": "Lebsackbury"
}
]
Source
In this article we have converted named lists and data frames to JSON, parsed
flat and nested values, and controlled the result with
simplifyVector and flatten. Missing values travelled
as null and returned as NA. We read live responses
from the GitHub API and JSONPlaceholder directly with fromJSON,
streamed JSON Lines with stream_out and stream_in,
and moved a data frame through a file with write_json and
read_json. The final example combined two endpoints into a
summary. The data frames and
apply family articles cover the tables and
the vapply and tapply calls used here, and the
tidyr article turns list columns into tidy rows.
For requests that need headers, a body, or error handling, see the
HTTP requests article.
Author
List all R Language tutorials.