R List to JSON: How to Use toJSON() Method in R

JSON is text, and we can convert from any data type into JSON and send that JSON to the server. All programming languages have support for json, and R is no different. Programming languages like PHP, Python, JavaScript, and C# have inbuilt support, but to work with json data in R, you need an external package and, after installing it, use its functions to convert any data type to json and json to any other data type.

R List to JSON

To convert an R object into a corresponding JSON object, use the toJSON() method. A list is an R object, so to convert the list to json, use the toJSON() object. The toJSON() is not an inbuilt R function. To use the toJSON() method, you need to install the rjson package.

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

install.packages("rjson")

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

library(rjson)

Now, you can use the toJSON() method to convert any R object to json. Let’s see the syntax of the toJSON() method.

Syntax

toJSON(data, indent=0, method="C" )

Parameters

dataIt is a Vector or List to convert into a JSON object.
indentIt is an integer specifying how much indentation to use when formatting the JSON object; if 0(zero), no pretty-formatting is used.
methodUse the C implementation or the older slower R implementation.

Value

A string containing the JSON object.

Steps to convert R List to JSON

  1. Import rjson package.
  2. Create two vectors.
  3. Convert Vectors to List.
  4. Use the toJSON() method to convert the list to json.

Step 1: Import rjson package

library(rjson)

Step 2: Create two vectors

rv1 <- 1:5
rv2 <- 6:10

Step 3: Convert vectors into list

To convert vectors into list, use the list() function.

data <- list(rv1, rv2)

Step 4: Use the toJSON() method

Pass the list to the toJSON() method to convert into the json value.

jsonData <- toJSON(data)

Let’s see the complete example.

library(rjson)

rv1 <- 1:5
rv2 <- 6:10

data <- list(rv1, rv2)

jsonData <- toJSON(data)

jsonData
typeof(jsonData)

Output

[1] "[[1,2,3,4,5],[6,7,8,9,10]]"
[1] "character"

That is it. We successfully converted the list object to the json object whose data type is character. Remember, the json is an object or structure, or format. It is not a data type. The data type is character. In other languages, the data type of json is String, but in R, it is a character.

See also

R List to Numeric

R List to Array

R List to Matrix

R List to data frame

R List to Vector

Leave a Comment