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

valq

使用JavaScript-like语法查询和提取结构化数据宏

1个不稳定版本

0.1.0 2021年12月19日

#1558编码

Download history 140/week @ 2024-04-07 346/week @ 2024-04-14 205/week @ 2024-04-21 218/week @ 2024-04-28 512/week @ 2024-05-05 535/week @ 2024-05-12 261/week @ 2024-05-19 283/week @ 2024-05-26 351/week @ 2024-06-02 312/week @ 2024-06-09 195/week @ 2024-06-16 328/week @ 2024-06-23 685/week @ 2024-06-30 357/week @ 2024-07-07 240/week @ 2024-07-14 382/week @ 2024-07-21

1,748每月下载次数

MIT许可证

24KB
440

valq — Docs.rs shield crates.io shield

valq提供了一个用于以非常简洁的方式查询和提取结构化数据值的宏,类似于JavaScript语法。

外观和感觉

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

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

目前,仅导出单个宏:query_value

query_value

查询结构化数据内部值的宏。

基本用法

// 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);

转换为指定类型

// 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)

提取内部值的可变引用

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));

无运行时依赖