Rust implementation of JMESPath, a query language for JSON.
Compiling JMESPath expressions
Use the jmespatch::compile
function to compile JMESPath expressions
into reusable Expression
structs. The Expression
struct can be
used multiple times on different values without having to recompile
the expression.
use jmespatch;
let expr = compile.unwrap;
// Parse some JSON data into a JMESPath variable
let json_str = "{\"foo\":{\"bar\":{\"baz\":true}}}";
let data = from_json.unwrap;
// Search the data with the compiled expression
let result = expr.search.unwrap;
assert_eq!;
You can get the original expression as a string and the parsed expression
AST from the Expression
struct:
use jmespatch;
use Ast;
let expr = compile.unwrap;
assert_eq!;
assert_eq!;
JMESPath variables
In order to evaluate expressions against a known data type, the
jmespatch::Variable
enum is used as both the input and output type.
More specifically, Rcvar
(or jmespatch::Rcvar
) is used to allow
shared, reference counted data to be used by the JMESPath interpreter at
runtime.
By default, Rcvar
is an std::rc::Rc<Variable>
. However, by specifying
the sync
feature, you can utilize an std::sync::Arc<Variable>
to
share Expression
structs across threads.
Any type that implements jmespatch::ToJmespath
can be used in a JMESPath
Expression. Various types have default ToJmespath
implementations,
including serde::ser::Serialize
. Because jmespatch::Variable
implements
serde::ser::Serialize
, many existing types can be searched without needing
an explicit coercion, and any type that needs coercion can be implemented
using serde's macros or code generation capabilities. This includes a
number of common types, including serde's serde_json::Value
enum.
The return value of searching data with JMESPath is also an Rcvar
.
Variable
has a number of helper methods that make it a data type that
can be used directly, or you can convert Variable
to any serde value
implementing serde::de::Deserialize
.
Custom Functions
You can register custom functions with a JMESPath expression by using
a custom Runtime
. When you call jmespatch::compile
, you are using a
shared Runtime
instance that is created lazily using lazy_static
.
This shared Runtime
utilizes all of the builtin JMESPath functions
by default. However, custom functions may be utilized by creating a custom
Runtime
and compiling expressions directly from the Runtime
.
use ;
use ;
// Create a new Runtime and register the builtin JMESPath functions.
let mut runtime = new;
runtime.register_builtin_functions;
// Create an identity string function that returns string values as-is.
runtime.register_function;
// You can also use normal closures as functions.
runtime.register_function;
let expr = runtime.compile.unwrap;
assert_eq!;
let expr = runtime.compile.unwrap;
assert_eq!;