fromJSON in R: How to Convert JSON To R Object in R

The fromJSON() function reads the content in JSON format and de-serializes it into R objects. JSON content is produced of logical values, integers, real numbers, strings, arrays using the key: value pairs. The toJSON and fromJSON methods use class-based mapping.

fromJSON in R

The fromJSON() is a built-in R function that converts a JSON object into an object. To convert a json to an R object, use the fromJSON() function.

Syntax

fromJSON( json_str, file, method = "C", unexpected.escape = "error", simplify = TRUE )

Arguments

json_string: It is a JSON object to convert.

file: It is the file name to read the json_string from; this can also be a URL. Only one of json_string or file must be supplied.

method: It is the use of the C implementation or the older slower  R implementation.

unexpected.escape: It is changed handling of unexpected escaped characters. Handling value should be one of “error“, “skip“, or “keep“; on unexpected characters issue an error, skip the character or keep the character.

simplify: If it is TRUE, attempt to convert json-encoded lists into vectors where appropriate. If FALSE, all json-encoded lists will be wrapped in a list even if they are all of the same data types.

Return Value

The fromJSON() method returns the object that corresponds to the JSON object.

Example

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 let’s write the code.

library(rjson)

op_1 <- fromJSON('[11, 19, 21]', simplify = TRUE)
op_1
typeof(op_1)

Output

[1] 11 19 21
[1] "double"

You can see that the fromJSON() method converted the JSON object to a double value which is an R Object. To check the data type in R, use the typeof() function.

Passing simplify = FALSE

You can also see that in the above example that we passed simplify = TRUE. If it is TRUE, it attempts to convert json-encoded lists into vectors where appropriate.

If we pass simplify = FALSE, all json-encoded lists will be wrapped in a list even if they are all of the same data types.

library(rjson)

op_2 <- fromJSON('[11, 19, 21]', simplify = FALSE)
op_2
typeof(op_2)

Output

[[1]]
[1] 11

[[2]]
[1] 19

[[3]]
[1] 21

[1] "list"

As you can see that it returns the list in the output.

That is it for the fromJSON() method in R.

Leave a Comment