Convert JSON string to JSON object using R

Viewed 1128

How to convert that to a json object in R package jsonlite?

the problem is I want to use an R function that expects a JSON object as argument. And I find myself doing toJSON(fromJSON(jsonStr)) every time I want to pass a JSON string just to change it's class to json.

jsonStr <- '{"radius": 200, "color": "blue"}'

r2d3(data = as_d3_data(toJSON(fromJSON(jsonStr))),script = 'whatever.js')
1 Answers

I find myself doing toJSON(fromJSON(jsonStr)) every time I want to pass a JSON string just to change it's class to json.

The idiomatic way to change the class of an object is:

class(jsonStr) <- "json"

To make sure the string is valid, might want to use jsonlite::validate(jsonStr) after assigning the class.(Thanks to @SybolixAU for pointing this out.)

Related