Learn R Programming

jsontools (version 0.1.0)

json_extract: Extract an element from JSON

Description

Extract an element at a given path.

Usage

json_extract(
  x,
  path,
  ptype = NULL,
  default = NULL,
  na = NA,
  wrap_scalars = FALSE,
  bigint_as_char = bigint_default()
)

Arguments

x

A JSON vector.

path

Path to element. This must be a valid JSONpath expression. For example "$.a.b[0] extracts the 1 in {"a": {"b": [1, 2]}}.

ptype

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

Default value if path doesn't exist or element at path is empty.

na

Default value if element of x is NA.

wrap_scalars

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.

bigint_as_char

Convert big integers to character? The option jsontools.bigint_as_char is used as default.

Value

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.

Examples

Run this code
# 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