How to Convert List to JSON in R

To convert a list to JSON in R, you can use the toJSON() function from the jsonlite package.

To install the latest version of the jsonlite package, use the following command.

install.packages("jsonlite")

After installing the package, you need to import the package using the following code to use its functionality.

library(jsonlite)

Syntax

toJSON(data, pretty = TRUE, auto_unbox = TRUE)

Parameters

data It is a Vector or List to convert into a JSON object.
pretty It prints Pretty JSON data.
auto_unbox If set to TRUE, it removes box brackets.

Return Value

A string containing the JSON object.

Visual Representation

Converting List to JSON in R

Example

# load the jsonlite package
library(jsonlite)

# create a list
main_list <- list(name = "Krunal Lathiya", age = 30, city = "Rajkot")

# convert the list to JSON
main_json <- toJSON(main_list, pretty = TRUE, auto_unbox = TRUE)

print(main_json)

Output

{
   "name": "Krunal Lathiya",
   "age": 30,
   "city": "Rajkot"
}

The pretty argument in toJSON() is valid for making the JSON output more readable, which can be especially helpful for debugging or presentation purposes.

The jsonlite package follows a convention that’s generally compatible with how JSON data is typically handled in web applications, making it a good choice for tasks involving web technologies.

Leave a Comment