json <- '{
"locations": [
{"name": "Seattle", "state": "WA"},
{"name": "New York", "state": "NY"},
{"name": "Bellevue", "state": "WA"},
{"name": "Olympia", "state": "WA"}
]
}'
## return a JSON string
jsonpath(json, "$..name") |>
cat("\n")
## return an R object
jsonpath(json, "$..name", as = "R")
## create a list with state and name as scalar vectors
lst <- as_r(json)
if (requireNamespace("jsonlite", quietly = TRUE)) {
## objects other than scalar character vectors are automatically
## coerced to JSON; use `auto_unbox = TRUE` to represent R scalar
## vectors in the object as JSON scalar vectors
jsonpath(lst, "$..name", auto_unbox = TRUE) |>
cat("\n")
## use I("Seattle") to coerce to a JSON object ["Seattle"]
jsonpath(I("Seattle"), "$[0]") |> cat("\n")
}
## a scalar character vector like "Seattle" is not valid JSON...
try(jsonpath("Seattle", "$"))
## ...but a double-quoted string is
jsonpath('"Seattle"', "$")
## different ordering of object names -- 'asis' (default) or 'sort'
json_obj <- '{"b": "1", "a": "2"}'
jsonpath(json_obj, "$") |> cat("\n")
jsonpath(json_obj, "$.*") |> cat("\n")
jsonpath(json_obj, "$", "sort") |> cat("\n")
jsonpath(json_obj, "$.*", "sort") |> cat("\n")
path <- "locations[?state == 'WA'].name | sort(@)"
jmespath(json, path) |>
cat("\n")
if (requireNamespace("jsonlite", quietly = TRUE)) {
## original filter always fails, e.g., '["WA"] != 'WA'
jmespath(lst, path) # empty result set, '[]'
## filter with unboxed state, and return unboxed name
jmespath(lst, "locations[?state[0] == 'WA'].name[0] | sort(@)") |>
cat("\n")
## automatically unbox scalar values when creating the JSON string
jmespath(lst, path, auto_unbox = TRUE) |>
cat("\n")
}
## jsonpointer 0-based arrays
jsonpointer(json, "/locations/0/name")
## document root "", sort selected element keys
jsonpointer('{"b": 0, "a": 1}', "", "sort", as = "R") |>
str()
## 'Key not found' -- path '/' searches for a 0-length key
try(jsonpointer('{"b": 0, "a": 1}', "/"))
Run the code above in your browser using DataLab