
Extract an element at a given path.
json_extract(
x,
path,
ptype = NULL,
default = NULL,
na = NA,
wrap_scalars = FALSE,
bigint_as_char = bigint_default()
)
A JSON vector.
Path to element. This must be a valid
JSONpath expression.
For example "$.a.b[0]
extracts the 1
in {"a": {"b": [1, 2]}}
.
Output type. If NULL
, the default, the output type is
determined by computing the common type across all elements. Use
new_json_array()
resp. new_json_object()
if you know every element is
an array resp. object. Mind that the return type will only be json2
.
Default value if path doesn't exist or element at path is empty.
Default value if element of x
is NA
.
Should scalar values be wrapped? Note that scalars are only wrapped if either
ptype
is new_json_array()
or json2
vector.
ptype
is NULL
and the elements are a mix of scalar values and arrays.
Convert big integers to character? The option
jsontools.bigint_as_char
is used as default.
A vector with class given by ptype
and length equal to x
. Mind
that for new_json_array()
and new_json_object()
the return type will
only be json2
.
# NOT RUN {
x1 <- '{"a": 1, "b": 2}'
json_extract(x1, "$.a")
json_extract('{"a": {"b": 1}}', "$.a")
# `NA` values stay `NA` ...
json_extract(c(NA_character_, x1), "$.a")
# ... but can return the value of `na` instead.
json_extract(c(NA_character_, x1), "$.a", na = 3)
# missing paths error by default ...
try(json_extract(x1, "$.c"))
# ... but can be replaced by the value of `default` instead.
json_extract(x1, "$.c", default = "not there")
# make sure to error if you don't get back an array
json_extract('{"a": [1]}', "$.a", ptype = new_json_array())
try(json_extract('{"a": {"b": 1}}', "$.a", ptype = new_json_array()))
# }
Run the code above in your browser using DataLab