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 3Character 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] TRUEValidation
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