gpt4 book ai didi

json - 删除没有结构的json文件中的嵌套属性

转载 作者:行者123 更新时间:2023-12-05 01:54:27 26 4
gpt4 key购买 nike

假设我有一个很大的 JSON 文件。我的目标是只删除该 JSON 中的嵌套字段并编写一个新文件。


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

我不知道如何删除这样的嵌套属性。

由于 json 非常复杂,我必须坚持使用 Map,因为我对结构不感兴趣。获取 nested 的值会给我一个 Value。我只想将值更改为 map ,然后像这样插入map.insert(String::from("nested"), nested);.

最佳答案

最直接的方法是使用 JSON Value type API 遍历根 JSON 对象的子元素,直到到达要删除或插入的项目。

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

关于json - 删除没有结构的json文件中的嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70609192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com