serde_json_path/ext.rs
1use serde_json::Value;
2
3use crate::{JsonPath, NodeList};
4
5/// Extension trait that allows for JSONPath queries directly on [`serde_json::Value`]
6///
7/// ## Usage
8/// ```rust
9/// use serde_json::json;
10/// use serde_json_path::{JsonPath, JsonPathExt};
11///
12/// # fn main() -> Result<(), serde_json_path::ParseError> {
13/// let value = json!({"foo": ["bar", "baz"]});
14/// let query = JsonPath::parse("$.foo[*]")?;
15/// let nodes = value.json_path(&query).all();
16/// assert_eq!(nodes, vec!["bar", "baz"]);
17/// # Ok(())
18/// # }
19/// ```
20pub trait JsonPathExt {
21 /// Query a [`serde_json::Value`] with a JSONPath query string
22 fn json_path(&self, path: &JsonPath) -> NodeList;
23}
24
25impl JsonPathExt for Value {
26 fn json_path(&self, path: &JsonPath) -> NodeList {
27 path.query(self)
28 }
29}