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"?
}
I cannot figure out how to remove such a nested attribute.
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");