valq

valq provides a macro for querying semi-structured ("JSON-ish") data with the JavaScript-like syntax.
Look & Feel:
let obj: Value = ...;
// without valq: tedious and_then() chain...
let deep = obj
.get
.and_then
.and_then
.and_then
.and_then;
// with valq: very concise and readable!
use query_value;
let deep = query_value!;
Installation
Add this to the Cargo.toml in your project:
[]
= "*"
For now, there is only single macro exported: query_value.
query_value! macro
A macro for querying, extracting and converting inner value of semi-structured data.
Basic Queries
// get field `foo` from JSON object `obj`
let foo = query_value!;
// get the first item of the nested JSON array `arr` in `obj`
let head = query_value!;
// more complex query, just works!
let abyss = query_value!;
Extracting Mutable Reference to Inner Value
use
let mut obj = json!;
// `->` syntax converts `Value` to typed value (see below)
assert_eq!;
assert_eq!;
Converting & Deserializing to Specified Type
// try to convert the queried value into `u64` using `as_u64()` method on that value.
// results in `None` in case of type mismatch
let foo_u64: = query_value!;
// in the context of mutable reference extraction (see below), `as_xxx_mut()` method is used instead.
let arr_vec: = query_value!;
use Deserialize;
use json;
use query_value;
let j = json!;
// try to deserialize the queried value into a value of type `Person`.
let author: = query_value!;
Unwrapping Query Results with Default Values
use json;
use query_value;
let obj = json!;
assert_eq!;
assert_eq!; // explicitly provided default
assert_eq!; // using u64::default()
Compatibility
The query_value! macro can be used with arbitrary data structure(to call, Value) that supports get(&self, idx) -> Option<&Value> method that retrieves a value at idx.
Extracting mutable reference is also supported if your Value supports get_mut(&mut self, idx) -> Option<&Value>.
Instances of compatible data structures:
serde_json::Valueserde_yaml::Valuetoml::Value- and more...