JSONPath (JSONPath v0.2.0)

Copy Markdown View Source

RFC-9535 compliant JSON Path evaluator.

Summary

Functions

Builds a JSON Path query JSONPath.AST.t/0. Returns {:ok, ast} or {:error, JSONPath.Error.t()}.

Same as build/1 but raises in case of error

Evaluates a JSON value against the given query string or parsed AST. Returns an {:ok, results} or {:error, JSONPath.Error.t()} tuple

Same as evaluate/2 but raises in case of error

Types

json()

@type json() ::
  nil
  | number()
  | String.t()
  | boolean()
  | [json()]
  | %{required(String.t()) => json()}

Functions

build(query)

@spec build(String.t()) :: {:ok, JSONPath.AST.t()} | {:error, JSONPath.Error.t()}

Builds a JSON Path query JSONPath.AST.t/0. Returns {:ok, ast} or {:error, JSONPath.Error.t()}.

Prefer this function when running the same query multiple times, since building the query each time performs potentially expensive semantic checks.

build!(query)

@spec build!(String.t()) :: JSONPath.AST.t()

Same as build/1 but raises in case of error

evaluate(document, query)

@spec evaluate(json(), String.t() | JSONPath.AST.t()) ::
  {:ok, [json()]} | {:error, JSONPath.Error.t()}

Evaluates a JSON value against the given query string or parsed AST. Returns an {:ok, results} or {:error, JSONPath.Error.t()} tuple

Examples

iex> JSONPath.evaluate(["aba", "bbab", "bab"], "$[?match(@, 'b.b')]")
{:ok, ["bab"]}

iex> JSONPath.evaluate(%{"foo" => [1, 2, 3, 4]}, "$.foo[::-1]")
{:ok, [4, 3, 2, 1]}

iex> JSONPath.evaluate(%{"foo" => %{"bar" => "baz"}}, "$[?length(@)]")
{:error, %JSONPath.Error{
  type: :invalid_expression,
  expression: "length(@)",
  message: "comparison operator expected"
  }
}

evaluate!(document, query)

@spec evaluate!(json(), String.t() | JSONPath.AST.t()) :: [json()]

Same as evaluate/2 but raises in case of error