Working with JSON Files in R Programming
JSON (JavaScript Object Notation) is a text-based format used to exchange structured data between applications. In R, a JSON object usually becomes a named list, a JSON array becomes a list or vector, and an array of similarly structured objects can often be converted into a data frame.
This tutorial explains how to install a JSON package, read JSON from a local file, inspect nested values, convert JSON records to a data frame, and write R data to a JSON file. The existing examples use the rjson package, followed by equivalent examples using jsonlite.
Install rjson
To work with JSON Files in R programming language, you may have to install rjson package.
Open R command window, and run the following command :
install.packages("rjson")
Output
trying URL 'https://mran.microsoft.com/snapshot/2017-09-01/bin/windows/contrib/3.4/rjson_0.2.15.zip'
Content type 'application/zip' length 564436 bytes (551 KB)
downloaded 551 KB
package ‘rjson’ successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\tutorialkart\AppData\Local\Temp\RtmpAruPYG\downloaded_packages
The installation output varies with the operating system, R version, selected CRAN mirror, and current package version. Install the package once, and then load it with library(rjson) in each new R session that uses it.
Read JSON File in R
To read JSON data from file in R programming language, import the rjson library, use fromJSON() function with the path to JSON File as argument.
For this example, save the following JSON text as sample-data.json in the current R working directory. You can check that directory by running getwd().
example.R
# load rjson package
library(rjson)
# read json file to variable
jsonData <- fromJSON(file = "sample-data.json")
# print json data
print(jsonData)
Output
[
{"name":"R Tutorial", "category":"Programming"},
{"name":"Go Tutorial", "category":"Programming"}
]
Console
> # Print the result.
> print(jsonData)
[[1]]
[[1]]$name
[1] "R Tutorial"
[[1]]$category
[1] "Programming"
[[2]]
[[2]]$name
[1] "Go Tutorial"
[[2]]$category
[1] "Programming"
>
The outer JSON array is returned as an R list. Each object inside the array becomes a named list. For example, use jsonData[[1]]$name to retrieve the name from the first record.
Resolve JSON File Paths in R
If R reports that it cannot open the JSON file, verify the working directory and the file path. A relative path is resolved from the value returned by getwd(). An absolute path identifies the file independently of the working directory.
# Display the current working directory
getwd()
# Confirm that the JSON file exists
file.exists("sample-data.json")
# Read a JSON file stored in a subdirectory
jsonData <- fromJSON(file = file.path("data", "sample-data.json"))
file.path() is useful when constructing portable paths because it uses the appropriate path separator for the operating system.
Access Nested JSON Values with rjson
Nested JSON objects become nested named lists. Use $ for a named element and double brackets for a list position. Consider a file named course.json containing a course object with a nested instructor object.
{
"title": "R Tutorial",
"active": true,
"lessons": 12,
"instructor": {
"name": "Alex",
"department": "Programming"
},
"topics": ["vectors", "lists", "data frames"]
}
library(rjson)
course <- fromJSON(file = "course.json")
course$title
course$instructor$name
course$topics[[2]]
[1] "R Tutorial"
[1] "Alex"
[1] "lists"
Convert JSON Records to an R Data Frame
When rjson::fromJSON() returns a list of records with the same fields, combine those records into a data frame with do.call() and rbind.
library(rjson)
jsonData <- fromJSON(file = "sample-data.json")
tutorials <- as.data.frame(do.call(rbind, jsonData), stringsAsFactors = FALSE)
print(tutorials)
name category
1 R Tutorial Programming
2 Go Tutorial Programming
This approach is suitable when every record has a compatible structure. Records containing different fields or deeply nested values may require explicit extraction and cleanup before they can form a rectangular data frame.
Write JSON Object to File
To write JSON Object to file, use toJSON() function of rjson library to prepare a JSON object and then use write() function for writing the JSON object to a local file.
example.R
# load rjson package
library(rjson)
list1 <- vector(mode="list", length=2)
list1[[1]] <- c("apple", "banana", "rose")
list1[[2]] <- c("fruit", "fruit", "flower")
# read list ot json
jsonData <- toJSON(list1)
# write json object to file
write(jsonData, "output.json")
Output
[["apple","banana","rose"],["fruit","fruit","flower"]]
The resulting output.json contains an outer array with two inner arrays. To create JSON objects with field names, start with a named R list.
library(rjson)
course <- list(
name = "R Tutorial",
category = "Programming",
published = TRUE
)
jsonText <- toJSON(course)
write(jsonText, file = "course-output.json")
{"name":"R Tutorial","category":"Programming","published":true}
Read and Write JSON with jsonlite in R
The jsonlite package provides another widely used interface for converting between JSON and R objects. Install it from CRAN, and then use fromJSON() to read a file or JSON string.
install.packages("jsonlite")
library(jsonlite)
# A uniform array of objects is simplified to a data frame
records <- fromJSON("sample-data.json")
print(records)
str(records)
By default, jsonlite::fromJSON() simplifies compatible arrays into vectors, matrices, or data frames. Set simplifyVector = FALSE when you need a list structure closer to the original JSON hierarchy.
library(jsonlite)
recordsAsList <- fromJSON(
"sample-data.json",
simplifyVector = FALSE
)
recordsAsList[[1]]$name
Write an R Data Frame to JSON with jsonlite
Use jsonlite::write_json() to serialize an R object and write it directly to a file. For a data frame, dataframe = "rows" produces an array in which each row is represented as a JSON object. The pretty = TRUE option adds indentation for readability.
library(jsonlite)
tutorials <- data.frame(
name = c("R Tutorial", "Go Tutorial"),
category = c("Programming", "Programming"),
stringsAsFactors = FALSE
)
write_json(
tutorials,
path = "tutorials.json",
dataframe = "rows",
pretty = TRUE,
auto_unbox = TRUE
)
[
{
"name": "R Tutorial",
"category": "Programming"
},
{
"name": "Go Tutorial",
"category": "Programming"
}
]
auto_unbox = TRUE writes length-one atomic vectors as scalar JSON values instead of one-element arrays. Choose this option according to the schema expected by the application that will consume the file.
Handle Missing Values and Dates in R JSON Output
JSON has no native R-specific representation for factors, dates, or NA. Check how these values should appear before exporting data. With jsonlite, you can explicitly select a date format and decide whether missing values should be written as JSON null or as strings.
library(jsonlite)
report <- data.frame(
created = as.Date(c("2026-01-10", "2026-01-11")),
score = c(95, NA)
)
write_json(
report,
path = "report.json",
dataframe = "rows",
date = "ISO8601",
na = "null",
pretty = TRUE
)
After writing a file, read it back and inspect the result. This round-trip check helps detect unexpected arrays, lost field names, incorrect date representations, and missing-value conversions.
library(jsonlite)
write_json(
tutorials,
"tutorials.json",
dataframe = "rows",
auto_unbox = TRUE
)
checkedData <- fromJSON("tutorials.json")
str(checkedData)
stopifnot(nrow(checkedData) == nrow(tutorials))
Common R JSON File Errors and Fixes
- Cannot open the connection: Check
getwd(), the filename, capitalization, andfile.exists(). - Lexical or parse error: Confirm that object keys and string values use double quotes, commas are correctly placed, and no trailing comma remains.
- Unexpected list instead of data frame: The JSON records may have inconsistent fields or nested values. Inspect the result with
str()before converting it. - Unexpected one-element arrays: When writing with
jsonlite, considerauto_unbox = TRUEif the receiving schema expects scalar values. - Package function conflict: Both packages define functions named
fromJSON()andtoJSON(). Use qualified names such asrjson::fromJSON()orjsonlite::fromJSON()when both packages are loaded. - Non-ASCII text appears incorrectly: Save and read JSON as UTF-8, and verify the encoding used by the source application.
R JSON File Editorial QA Checklist
- Confirm that every sample JSON document has valid double-quoted keys and strings.
- Verify that each filename used in R code matches the filename described in the surrounding instructions.
- Run the
rjsonandjsonliteexamples separately so the shared function names do not mask one another. - Check whether each parsed value is a list, vector, matrix, or data frame with
str(). - Read every generated JSON file back into R and compare its rows, field names, missing values, and nested structure with the source object.
- Confirm that output blocks show JSON file contents or R console results as labelled.
Frequently Asked Questions about JSON Files in R
What is a JSON file in R?
A JSON file is a text file containing objects, arrays, strings, numbers, Boolean values, or null. R packages such as rjson and jsonlite parse that text into R lists, vectors, matrices, or data frames.
How do I open a JSON file in R?
Load a JSON package and pass the file path to fromJSON(). For example, use jsonlite::fromJSON("sample-data.json"). If the file is not in the working directory, provide a relative path created with file.path() or an absolute path.
How do I write a JSON file in R?
With rjson, convert the object using toJSON() and save the returned text with write(). With jsonlite, write_json() converts the R object and writes the JSON file in one operation.
How do I convert JSON to a data frame in R?
jsonlite::fromJSON() normally simplifies a uniform array of JSON objects into a data frame. With rjson, a uniform list of records can be combined using as.data.frame(do.call(rbind, jsonData)). Irregular or nested records need additional transformation.
What is the difference between rjson and jsonlite?
Both packages convert JSON and R objects. rjson commonly represents parsed JSON as lists and uses toJSON() to produce JSON text. jsonlite can simplify compatible arrays into data frames and provides options for data-frame orientation, scalar unboxing, missing values, dates, and formatted output.
R JSON Reading and Writing Summary
In this R Tutorial – Working with JSON Files, we have learnt to read JSON data from a JSON file and write a JSON Object to a local File using rjson library with example R scripts.
Use str() after parsing to understand the resulting R structure. For uniform record-oriented data, jsonlite can convert JSON arrays directly to data frames and write data frames as row-oriented JSON. For either package, verify file paths, handle nested and missing values deliberately, and read generated files back into R before using them in another application.
TutorialKart.com