Welcome to ClientVPS Mirrors

Parsing JSON

Parsing JSON

library(RJSONIO)

fromJSON() parses JSON arrays, objects, strings, numbers, booleans, and nulls. The return type depends on the JSON shape and the simplification settings.

Parse JSON text

fromJSON("[1, 3, 10, 19]")
#> [1]  1  3 10 19

fromJSON('{"a": 1, "b": true, "c": "value"}')
#> $a
#> [1] 1
#> 
#> $b
#> [1] TRUE
#> 
#> $c
#> [1] "value"

Use I() when passing JSON text that should be treated explicitly as content.

fromJSON(I("[3.1415]"))
#> [1] 3.1415

Parse files

File paths are read from disk when asText = FALSE, which is the default for plain character strings that do not look like JSON content.

path <- system.file("sampleData", "keys.json", package = "RJSONIO")
parsed <- fromJSON(path)

names(parsed)
#> [1] "menu"
names(parsed$menu)
#> [1] "header" "items"

Parse connections

Connections are useful when JSON content is already available through an R connection object.

con <- textConnection(c("[[1, 2, 3, 4],", "[5, 6, 7, 8]]"))
parsed <- fromJSON(con)
close(con)

parsed
#> [[1]]
#> [1] 1 2 3 4
#> 
#> [[2]]
#> [1] 5 6 7 8

Null values

By default, JSON null maps to NULL in list output. Use nullValue to preserve positions in simplified vectors.

fromJSON("[1, null, 4]", simplify = FALSE)
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> NULL
#> 
#> [[3]]
#> [1] 4
fromJSON("[1, null, 4]", simplify = TRUE, nullValue = -999)
#> [1]    1 -999    4

Simplification

Strict simplification keeps incompatible values as lists. Less strict simplification can coerce mixed compatible values into an atomic vector.

fromJSON('[1, "2.3", "abc"]', simplify = Strict)
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] "2.3"
#> 
#> [[3]]
#> [1] "abc"
fromJSON('[1, "2.3", "abc"]', simplify = TRUE)
#> [1] "1.000000" "2.3"      "abc"
fromJSON('{"a": 1, "b": 2}', simplify = Strict)
#> a b 
#> 1 2
fromJSON('{"a": 1, "b": 2}', simplify = FALSE)
#> $a
#> [1] 1
#> 
#> $b
#> [1] 2

Sample data

The package includes JSON fixtures that are useful for examples and local checks.

sample_dir <- system.file("sampleData", package = "RJSONIO")
head(list.files(sample_dir, pattern = "[.]json$"))
#> [1] "array.json"    "array2.json"   "array3.json"   "embedded.json"
#> [5] "glossay.json"  "int.json"

widget <- fromJSON(file.path(sample_dir, "widget.json"))
names(widget)
#> [1] "widget"

Need a high-speed mirror for your open-source project?
Contact our mirror admin team at info@clientvps.com.

This archive is provided as a free public service to the community.
Proudly supported by infrastructure from VPSPulse , RxServers , BuyNumber , UnitVPS , OffshoreName and secure payment technology by ArionPay.