Skip to content

The [[ operator works similarly to the combination of ts_tree_select() and ts_tree_unserialize(), but it might be more readable.

Usage

# S3 method for class 'ts_tree'
x[[i, ...]]

Arguments

x

A ts_tree object.

i

Selection expressions in a list, see details in ts_tree_select().

...

Additional arguments, passed to ts_tree_select().

Value

List of R objects, with one entry for each selected element.

Details

The following two expressions are equivalent:

 

ts_tree_select(tree, <selectors>) |> ts_tree_unserialize()
and

 

tree[[list(<selectors>)]]

 

json <- tsjsonc::ts_parse_jsonc(
  '{ "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": null } }'
)
json |> ts_tree_select("b", 1)
#> # jsonc (1 line, 1 selected element)
#> > 1 | { "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": null } }

 

json[[list("b", 1)]]
#> [[1]]
#> [1] 10
#>

The [[<- replacement operator

The [[<- operator works similarly to the combination of ts_tree_select() and ts_tree_update(), (and also to the replacement function ts_tree_select<-()), but it might be more readable.

 

json <- tsjsonc::ts_parse_jsonc(
  '{ "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": null } }'
)
json

#> # jsonc (1 line)
#> 1 | { "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": null } }

 

json |> ts_tree_select("b", 1)

#> # jsonc (1 line, 1 selected element)
#> > 1 | { "a": 1, "b": [10, 20, 30], "c": { "c1": true, "c2": null } }

 

json[[list("b", 1)]] <- 100
json

#> # jsonc (1 line)
#> 1 | { "a": 1, "b": [100, 20, 30], "c": { "c1": true, "c2": null } }

Examples

# Create a parse tree with tsjsonc -------------------------------------
tree <- tsjsonc::ts_parse_jsonc('{"a": 13, "b": [1, 2, 3], "c": "x"}')

tree
#> # jsonc (1 line)
#> 1 | {"a": 13, "b": [1, 2, 3], "c": "x"}

tree[[list("a")]]
#> [[1]]
#> [1] 13
#> 

# Last two elements of "b"
tree[[list("b", -(1:2))]]
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 3
#>