Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove nested attribute in json file without structs, in rust?

Assuming I have a big JSON file.
My goal is to just remove a nested field within that JSON and write a new file.


use serde_json::Value;
use serde_json::Map;

fn main() {
    let data = r#"{
                    "name": "John Doe",
                    "age": 43,
                    "nested":{
                        "to.be.removed": [
                          "+44 1234567",
                          "+44 2345678"
                        ],
                        "other": "important fields"

                    }
                  }"#;

    let mut map :Map<String, Value> =serde_json::from_str(data).expect("failed to read file");
    // how do i remove  "to.be.removed"?


}

Playground

I cannot figure out how to remove such a nested attribute.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since the json is quite complex, i have to stick to a Map as i am not interested in structs. Fetching the value of nested renders me a Value. I would just like to change the value into a map to then insert like this
map.insert(String::from("nested"), nested);.

>Solution :

The most straightforward way is to use the JSON Value type API to traverse into children elements of the root JSON object until you reach the items to remove or insert.

let data = r#"{
    "name": "John Doe",
    "age": 43,
    "nested":{
        "to.be.removed": [
          "+44 1234567",
          "+44 2345678"
        ],
        "other": "important fields"

    }
}"#;
let mut map: Map<String, Value> = serde_json::from_str(data)
    .expect("failed to read file");

// get to the nested object "nested"
let nested = map.get_mut("nested")
    .expect("should exist")
    .as_object_mut()
    .expect("should be an object");

// now remove the child from there
nested.remove("to.be.removed");

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading