Parsing JSON with jsonlite
Convert JSON strings to R lists and data frames with fromJSON().
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 # NAAll lessons in this course
- Parsing JSON with jsonlite
- Making HTTP Requests with httr2
- Consuming REST APIs in R
- Handling Nested JSON Structures