How to Read JSON in R: Simple Guide with Examples
To read JSON in R, use the
fromJSON() function from the jsonlite package. This function converts JSON text or files into R objects like lists or data frames for easy use.Syntax
The main function to read JSON in R is fromJSON() from the jsonlite package.
fromJSON(txt): Reads JSON from a string or file path.txt: A JSON string or a path to a JSON file.- The function returns an R object such as a list or data frame depending on the JSON structure.
r
library(jsonlite) # Basic syntax to read JSON from a file or string result <- fromJSON(txt = "path_or_json_string")
Example
This example shows how to read JSON data from a string and convert it into an R list.
r
library(jsonlite) json_text <- '{"name": "Alice", "age": 30, "city": "New York"}' data <- fromJSON(json_text) print(data)
Output
{
name: "Alice",
age: 30,
city: "New York"
}
Common Pitfalls
Common mistakes when reading JSON in R include:
- Not installing or loading the
jsonlitepackage before usingfromJSON(). - Passing invalid JSON strings or incorrect file paths.
- Expecting a data frame when the JSON structure is nested or complex, which returns a list instead.
Always validate your JSON format and check the returned object's structure.
r
# Wrong: Missing library load # data <- fromJSON('{"key": "value"}') # Error if jsonlite not loaded # Right: library(jsonlite) data <- fromJSON('{"key": "value"}') print(data)
Output
{
key: "value"
}
Quick Reference
| Function | Description |
|---|---|
| fromJSON(txt) | Reads JSON string or file and converts to R object |
| toJSON(object) | Converts R object back to JSON string |
| validate(json) | Checks if JSON string is valid |
Key Takeaways
Use the jsonlite package and its fromJSON() function to read JSON in R.
fromJSON() can read JSON from strings or files and returns lists or data frames.
Always load jsonlite with library(jsonlite) before calling fromJSON().
Check your JSON format and the structure of the returned R object.
Use validate() to confirm JSON validity before parsing.