Function jsonpath_lib::replace_with[][src]

pub fn replace_with<F>(
    value: Value,
    path: &str,
    fun: &mut F
) -> Result<Value, JsonPathError> where
    F: FnMut(Value) -> Option<Value>, 
Expand description

Select JSON properties using a jsonpath and transform the result and then replace it. via closure that implements FnMut you can transform the selected results.

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

use serde_json::Value;

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

let ret = jsonpath::replace_with(json_obj, "$..[?(@.age == 20)].age", &mut |v| {
    let age = if let Value::Number(n) = v {
        n.as_u64().unwrap() * 2
    } else {
        0
    };

    Some(json!(age))
}).unwrap();

assert_eq!(ret, json!({
    "school": {
        "friends": [
            {"name": "친구1", "age": 40},
            {"name": "친구2", "age": 40}
        ]
    },
    "friends": [
        {"name": "친구3", "age": 30},
        {"name": "친구4"}
]}));