Convert data objects into the JSON text object

The toJSON() method can be used to convert the data objects into the JSON text object. The method has the following syntax : 

Syntax: toJSON(R-object-text)

Parameters : 

R-object-text – The data contained in R object.

R




# Importing rjson
library(rjson)
# creating a data frame
data_frame <- data.frame(col1=c(1: 5),
                          col2=letters[1:5],
                          col3=c("Commerce",
                                 "Humanities",
                                 "CSE",
                                 "Commerce",
                                 "Humanities")
                          )
# printing the data frame
print("Data Frame")
print(data_frame)
# converting to json object
json_obj = toJSON(data_frame)
# printing the json
print("JSON")
print(json_obj)


Output:

[1] "Data Frame"
 col1 col2       col3
1    1    a   Commerce
2    2    b Humanities
3    3    c        CSE
4    4    d   Commerce
5    5    e Humanities
[1] "JSON"
[1] "{\"col1\":[1,2,3,4,5],\"col2\":[\"a\",\"b\",\"c\",\"d\",\"e\"],\"col3\":[\"Commerce\",\"Humanities\",\"CSE\",\"Commerce\",\"Humanities\"]}"

Convert R objects to/from JSON in jsonlite

In this article, we are going to know how to convert R objects to/from JSON in jsonlite using the R programming language.

jsonlite package

The jsonlite package in R is used to simulate the conversion to and from the JSON data objects in R. It can be converted easily to other data objects. The package can be downloaded and installed into the R working space using the following command.

install.packages("jsonlite")

Similar Reads

Parse JSON in R

The JSON text in R is enclosed within the curly braces surrounded by string. The fromJSON() method in the rjson package is used to convert the JSON data into a text string. Each key becomes the header and the values to which they correspond are displayed as strings under the row numbers. This method performs the deserialization of the JSON data. It converts the data into an equivalent R object. The method has the following syntax :...

Convert JSON text into a data frame

...

Convert data objects into the JSON text object

The JSON text can also be converted to a data frame. The R object can be used to visualize data in a much more organized tabular structure. After the conversion of the JSON text, it can be subjected to the as.data.frame() method which coerces it into a data frame object. The keys of the JSON text are displayed as column headers of the data frame and the values are the cell values....

Convert list objects into JSON data

...