Current section
Files
Jump to
Current section
Files
lib/jsonpath_ex.ex
defmodule JSONPathEx do
@moduledoc """
Main interface for the JSONPathEx library.
JSONPathEx provides tools to parse and evaluate JSONPath expressions
against JSON data. This module serves as the main entry point, combining
parsing and evaluation into a single, convenient function.
## Features
- Parse JSONPath expressions into Abstract Syntax Trees (ASTs).
- Evaluate JSONPath expressions or ASTs against JSON data.
- Supports filters, recursive descent, array slicing, logical operators,
arithmetic, `in`/`nin`, nested filters, shorthand filter syntax (`[?expr]`),
full RFC 9535 escape sequences in quoted keys, quoted dot-child, unicode
member names, scientific-notation floats, and built-in functions
(`length`, `count`, `min`, `max`, `sum`, `avg`, `concat`, `match`, `search`)
in both postfix (`.length()`) and prefix (`length(@)`) styles.
## Examples
iex> json_data = %{
...> "store" => %{
...> "book" => [
...> %{
...> "category" => "reference",
...> "author" => "Nigel Rees",
...> "title" => "Sayings of the Century",
...> "price" => 8.95
...> }
...> ]
...> }
...> }
iex> JSONPathEx.evaluate("$.store.book[*].title", json_data)
{:ok, ["Sayings of the Century"]}
"""
alias JSONPathEx.{Parser, Evaluator}
@doc """
Parses and evaluates a JSONPath expression against the provided JSON data.
Combines parsing and evaluation. Returns `{:ok, result}` on success or
`{:error, message}` on parse failure.
## Parameters
- `expression` (String): A valid JSONPath expression.
- `json_data` (Map or List or scalar): The JSON data to query.
## Examples
iex> json_data = %{
...> "store" => %{
...> "book" => [
...> %{"title" => "Elixir in Action"},
...> %{"title" => "Programming Elixir"}
...> ]
...> }
...> }
iex> JSONPathEx.evaluate("$.store.book[*].title", json_data)
{:ok, ["Elixir in Action", "Programming Elixir"]}
## Errors
iex> {:error, msg} = JSONPathEx.evaluate("$.invalid[", %{})
iex> String.contains?(msg, "parse error") or String.contains?(msg, "unexpected")
true
"""
def evaluate(expression, json_data) do
case Parser.parse(expression) do
{:ok, ast} -> {:ok, Evaluator.evaluate(ast, json_data)}
error -> error
end
end
@doc """
Like `evaluate/2` but raises on parse error and returns the result directly.
"""
def evaluate!(expression, json_data) do
case evaluate(expression, json_data) do
{:ok, result} -> result
{:error, message} -> raise ArgumentError, "JSONPathEx: #{message}"
end
end
@doc """
Parses a JSONPath expression into an Abstract Syntax Tree (AST).
## Examples
iex> JSONPathEx.parse("$.store.book[*].title")
{:ok, [root: "$", dot_child: ["store"], dot_child: ["book"], array: [array_wildcard: {:wildcard, "*"}], dot_child: ["title"]]}
"""
def parse(expression), do: Parser.parse(expression)
end