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
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.