Function jsonpath_lib::selector_as

source ·
pub fn selector_as<'a, T: DeserializeOwned>(
    json: &'a Value
) -> impl FnMut(&'a str) -> Result<Vec<T>, JsonPathError> + '_
Expand description

It is the same to selector function. but it deserialize the result as given type T.

extern crate jsonpath_lib as jsonpath;
extern crate serde;
#[macro_use] extern crate serde_json;

use serde::{Deserialize, Serialize};

let json_obj = json!({
    "school": {
        "friends": [
            {"name": "친구1", "age": 20},
            {"name": "친구2", "age": 20}
        ]
    },
    "friends": [
        {"name": "친구3", "age": 30},
        {"name": "친구4"}
]});

#[derive(Deserialize, PartialEq, Debug)]
struct Friend {
    name: String,
    age: Option<u8>,
}

let mut selector = jsonpath::selector_as::<Friend>(&json_obj);

let json = selector("$..friends[0]").unwrap();

let ret = vec!(
    Friend { name: "친구3".to_string(), age: Some(30) },
    Friend { name: "친구1".to_string(), age: Some(20) }
);
assert_eq!(json, ret);

let json = selector("$..friends[1]").unwrap();

let ret = vec!(
    Friend { name: "친구4".to_string(), age: None },
    Friend { name: "친구2".to_string(), age: Some(20) }
);

assert_eq!(json, ret);