serde_json_path icon indicating copy to clipboard operation
serde_json_path copied to clipboard

Mutable NodeList or modifying query results

Open robert-mac-wbt opened this issue 1 year ago • 6 comments

Hello 👋

I wanted to ask if it's possible to do something following with this crate. I want to be able to run multiple queries on some json in order to eventually find a node that I'd like to modify/remove. In the following example, I'm trying to remove genre of the second book in the list.

use serde_json::Value;
use serde_json_path::{JsonPath, JsonPathExt};

fn main() {
    let data = r#"
    {
        "books": [
            {
                "title": "Title 1",
                "details": {
                    "description": "Description 1",
                    "genre": "Genre 1"
                }

            },
            {
                "title": "Title 2",
                "details": {
                    "description": "Description 1",
                    "genre": "Genre 2"
                }
            }
        ]
    }
  "#;

    let some_json: Value = serde_json::from_str(data).expect("failed to read file");
    let books_path = JsonPath::parse("$.books").unwrap();
    let genre_path = JsonPath::parse("$.details.genre").unwrap();

    let nodes = some_json.json_path(&books_path).exactly_one().unwrap().as_array().unwrap();
    let second_node = nodes.get(1).unwrap();
    let genre_node = second_node.json_path(&genre_path).exactly_one().unwrap();

    //  remove genre_node
}

Do you have any suggestion how to achieve this? Even after changing second_node to an object, I'm getting an error saying that it's not mutable. Or maybe adding mutable nodelists could help here? Currently after querying &Value are returned.

Thanks!

robert-mac-wbt avatar Oct 30 '23 04:10 robert-mac-wbt