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.
fromJSON( json_str, file, method = "C", unexpected.escape = "error", simplify = TRUE )
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.
The fromJSON() method returns the object that corresponds to the JSON object.
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.
After installing the package, now to use its functionality, you need to import the package using the following code.
Now let’s write the code.
library(rjson) op_1 <- fromJSON('[11, 19, 21]', simplify = TRUE) op_1 typeof(op_1)
 11 19 21  "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)
[]  11 []  19 []  21  "list"
As you can see that it returns the list in the output.
That is it for the fromJSON() method in R.