#serde-json #json #query #serde #macro #extract

valq

macros for querying and extracting value from structured data by JavaScript-like syntax

1 unstable release

0.1.0 Dec 19, 2021

#1573 in Encoding

Download history 326/week @ 2024-06-01 313/week @ 2024-06-08 181/week @ 2024-06-15 289/week @ 2024-06-22 721/week @ 2024-06-29 390/week @ 2024-07-06 235/week @ 2024-07-13 356/week @ 2024-07-20 258/week @ 2024-07-27 522/week @ 2024-08-03 722/week @ 2024-08-10 371/week @ 2024-08-17 587/week @ 2024-08-24 654/week @ 2024-08-31 1344/week @ 2024-09-07 491/week @ 2024-09-14

3,084 downloads per month

MIT license

24KB
440 lines

valq   Docs.rs shield crates.io shield

valq provides a macro for querying and extracting value from structured data in very concise manner, like the JavaScript syntax.

Look & Feel:

use serde_json::Value;
use valq::query_value;

let j: Value = ...;
let deep_val: Option<&Value> = query_value!(j.path.to.value.at.deep);

For now, there is only single macro exported: query_value.

query_value macro

A macro for querying inner value of structured data.

Basic Usage

// get field `foo` from JSON object `obj`
let foo = query_value!(obj.foo);

// get nested field `bar` inside object `foo` in JSON object `obj`
let bar = query_value!(obj.foo.bar);

// get head of JSON array 'arr'
let head = query_value!(arr[0]);

// get head of nested JSON array `arr` in JSON object `obj`
let head = query_value!(obj.arr[0]);

// more complex example!
let abyss = query_value!(obj.path.to.matrix[0][1].abyss);

Converting to Specified Type

// try to convert extracted value to `u64` by `as_u64()` method  on that value.
// results in `None` in case of type mismatch
let foo_u64: Option<u64> = query_value!(obj.foo -> u64)

// in case of mutable reference extraction (see below), `as_xxx_mut()` method will be used.
let arr_vec: Option<&mut Vec<Value>> = query_value!(mut obj.arr -> array)

Extracting Mutable Reference to Inner Value

use serde_json::{json, Value}

let mut obj = json!({"foo": { "bar": { "x": 1, "y": 2 }}});
{
    // prefixed `mut` means extracting mutable reference
    let bar: &mut Value = query_value!(mut obj.foo.bar).unwrap();
    *bar = json!({"x": 100, "y": 200});
}
assert_eq!(query_value!(obj.foo.bar.x -> u64), Some(100));
assert_eq!(query_value!(obj.foo.bar.y -> u64), Some(200));

No runtime deps