List as JSON string in R

Viewed 341

Problem: I want to convert a list object into a JSON string. In Python I can easily do this with json.dumps() with dictionary object.

How can I do this in R?

library(jsonlite)

a <- list(y = list(x = c(1, 2, 3), y = c(3, 4, 5)))
toJSON(a)

## Expected Outcome
"[{\"y\":{\"x\":[1,2,3],\"y\":[3,4,5]}}]"
1 Answers

The returned object from toJSON is of class "json", and it has its own print method so you can see the json string without distracting escape characters (similar to base R's cat function). To make it a standard character vector you just do:

as.character(toJSON(a))
#> [1] "{\"y\":{\"x\":[1,2,3],\"y\":[3,4,5]}}"
Related