Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add a value at a path? #18

Open
gkorland opened this issue Jul 17, 2019 · 2 comments
Open

How to add a value at a path? #18

gkorland opened this issue Jul 17, 2019 · 2 comments

Comments

@gkorland
Copy link
Contributor

e.g.

{ 
   "a" : {
       "b": 1
   }
}

Add $.a.c=2
to:

{ 
   "a" : { 
       "b": 1,
       "c": 2
   }
}
@freestrings
Copy link
Owner

if a value exist in a given path as above, you can use the replace_with function.

fn add(
    json: serde_json::Value,
    path: &str,
    key: &str,
    value: serde_json::Value,
) -> Result<Option<serde_json::Value>, jsonpath::JsonPathError> {
    let mut wrap = Box::new(value);
    let mut selector = jsonpath::SelectorMut::new();
    let ret = selector
        .value(json)
        .str_path(path)?
        .replace_with(&mut |found| {
            let mut ret = found.clone();
            if let serde_json::Value::Object(ref mut map) = ret {
                map.insert(key.to_string(), wrap.take());
            }
            ret
        })?
        .take();
    Ok(ret)
}

fn main() -> Result<(), jsonpath::JsonPathError> {
    let ret = add(
        json!(
            {
                "a" : {
                    "b" : 1
                }
            }
        ),
        "$.a",
        "c",
        json!(2),
    )?;

    println!("{:?}", ret);
    Ok(())
}

@gkorland
Copy link
Contributor Author

The thing is that we're getting a string path from the user and it's hard to remove the last part of the path so we can find the right place to add the new node.

e.g. in this simple example we'll get $.a.c from the user and will have to do parse the path and remove the last .c

gkorland referenced this issue in gkorland/jsonpath Aug 27, 2019
ref #18 exposing the parsing results will allow us to use the ParseTokens to add new paths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants