gpt4 book ai didi

json - 如何迭代层次结构中的 JSON 对象?

转载 作者:行者123 更新时间:2023-11-29 07:55:32 24 4
gpt4 key购买 nike

我想打印层次结构深处对象中每个联系人的名称。联系人对象可能不会每次都具有完全相同数量的字段来构建合适的结构。我怎样才能做到这一点?

extern crate serde_json;

use serde_json::{Error, Value};
use std::collections::HashMap;

fn untyped_example() -> Result<(), Error> {
// Some JSON input data as a &str. Maybe this comes from the user.
let data = r#"{
"name":"John Doe",
"age":43,
"phones":[
"+44 1234567",
"+44 2345678"
],
"contact":{
"name":"Stefan",
"age":23,
"optionalfield":"dummy field",
"phones":[
"12123",
"345346"
],
"contact":{
"name":"James",
"age":34,
"phones":[
"23425",
"98734"
]
}
}
}"#;

let mut d: HashMap<String, Value> = serde_json::from_str(&data)?;
for (str, val) in d {
println!("{}", str);
if str == "contact" {
d = serde_json::from_value(val)?;
}
}

Ok(())
}

fn main() {
untyped_example().unwrap();
}

我是 Rust 的新手,基本上来自 JavaScript 背景。

最佳答案

may not have the exact same number of fields every time to make a suitable structure

不清楚你为什么这么想:

extern crate serde_json; // 1.0.24
#[macro_use]
extern crate serde_derive; // 1.0.70;

use serde_json::Error;

#[derive(Debug, Deserialize)]
struct Contact {
name: String,
contact: Option<Box<Contact>>,
}

impl Contact {
fn print_names(&self) {
println!("{}", self.name);

let mut current = self;

while let Some(ref c) = current.contact {
println!("{}", c.name);

current = &c;
}
}
}

fn main() -> Result<(), Error> {
let data = r#"{
"name":"John Doe",
"contact":{
"name":"Stefan",
"contact":{
"name":"James"
}
}
}"#;

let person: Contact = serde_json::from_str(data)?;
person.print_names();

Ok(())
}

我已经从 JSON 中删除了额外的字段以提供一个更小的示例,但如果它们存在则不会有任何变化。

另见:

关于json - 如何迭代层次结构中的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51899190/

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