2

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')
Frank
  • 66,179
  • 8
  • 96
  • 180
M.AbdAllah
  • 25
  • 5

1 Answers1

4

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.)

Frank
  • 66,179
  • 8
  • 96
  • 180
  • (I couldn't find a dupe so am making my comment into an answer. Happy to delete it if a good dupe target is found) – Frank Jun 28 '19 at 19:04
  • 1
    might want to use `jsonlite::validate(jsonStr)` to validate it after assigning the class – SymbolixAU Jul 01 '19 at 03:30