Skip to contents

RJSONIO converts data between R objects and JSON text. The main entry points are fromJSON() for parsing JSON and toJSON() for serializing R objects.

Basic parsing

Use fromJSON() with JSON text, a file path, or a connection.

fromJSON('{"name": "RJSONIO", "active": true, "values": [1, 2, 3]}')
#> $name
#> [1] "RJSONIO"
#> 
#> $active
#> [1] TRUE
#> 
#> $values
#> [1] 1 2 3

Character input that starts with { or [ is treated as JSON content. A plain file path is read from disk.

path <- system.file("sampleData", "keys.json", package = "RJSONIO")
names(fromJSON(path))
#> [1] "menu"

Basic serialization

Use toJSON() to serialize common R objects.

value <- list(
  id = 1,
  name = "RJSONIO",
  values = c(1, 2, 3),
  active = TRUE
)

json <- toJSON(value, pretty = TRUE)
cat(json)
#> {
#>  "id" : 1,
#>  "name" : "RJSONIO",
#>  "values" : [
#>      1,
#>      2,
#>      3
#>  ],
#>  "active" : true
#> }

The result can be parsed back into R.

fromJSON(json)
#> $id
#> [1] 1
#> 
#> $name
#> [1] "RJSONIO"
#> 
#> $values
#> [1] 1 2 3
#> 
#> $active
#> [1] TRUE

Validation

isValidJSON() checks whether JSON text can be parsed.

candidate <- toJSON(list(name = "RJSONIO", version = "2.0.3"))
isValidJSON(I(candidate))
#> [1] TRUE
isValidJSON(I("{not valid json}"))
#> [1] FALSE

Round trips

Round trips are most direct for simple vectors and lists whose JSON representation maps cleanly back to base R types.

value <- list(a = 1, b = c(TRUE, FALSE), c = c("x", "y"))
parsed <- fromJSON(toJSON(value))

identical(parsed, value)
#> [1] TRUE
parsed
#> $a
#> [1] 1
#> 
#> $b
#> [1]  TRUE FALSE
#> 
#> $c
#> [1] "x" "y"