我有下面的 JSON 数据,我需要使用 Rust 解析它。使用 serde,我可以访问一些 JSON:
let v: serde_json::Value = serde_json::from_str(&data).expect("Unable to parse");
let sessions = v["data"]["sessions"].as_array().unwrap();
let programs = v["data"]["programs"].as_array().unwrap();
但是如何使用
programData
值过滤单个 programs.id
数组项?我正在尝试这样的事情,但我做不到:
for x in programs {
let programId = &x["id"];
// not working - produces 'no implementation' error while building
let programSessions = sessions.iter().filter(|&f| f["programData"].as_array().unwrap()["programRefId"] == programId).collect();
}
{
"data": {
"name": "my name",
"sessions": [
{
"id": 1,
"programData": [
{
"dataPhase": 1,
"programRefId": 2,
"programSpecificData": {
"completed": false
}
},
{
"dataPhase": 2,
"programRefId": 3,
"programSpecificData": {
"completed": true
}
}
]
}
],
"programs": [
{
"id": 3
}
]
}
}
如果您想使用
programData
过滤单个 program.id
数组项,您需要更改一些内容。看起来您正在直接将嵌套结构中的 serde_json::Value
与另一个 serde_json::Value
进行比较,这可能会导致问题。您还尝试对 programData
进行过滤,就好像它是单个对象,而实际上它是一个数组。
您应该循环遍历每个程序,然后对于每个程序循环遍历每个会话,然后在每个会话过滤器中基于
programData
的项目。programRefId
Rust Playground 链接use serde_json::Value;
fn main() {
let data = r#"
{
"data": {
"name": "my name",
"sessions": [
{
"id": 1,
"programData": [
{
"dataPhase": 1,
"programRefId": 2,
"programSpecificData": {
"completed": false
}
},
{
"dataPhase": 2,
"programRefId": 3,
"programSpecificData": {
"completed": true
}
}
]
}
],
"programs": [
{
"id": 3
}
]
}
}
"#;
let v: Value = serde_json::from_str(data).expect("Unable to parse");
let sessions = v["data"]["sessions"].as_array().unwrap();
let programs = v["data"]["programs"].as_array().unwrap();
for program in programs {
let program_id = program["id"].as_i64().unwrap(); // Assuming id is always an integer.
for session in sessions {
let program_data = session["programData"].as_array().unwrap();
let program_sessions: Vec<&Value> = program_data.iter().filter(|&f| {
// Assuming programRefId is always present and an integer.
f["programRefId"].as_i64() == Some(program_id)
}).collect();
// Now you have the filtered programSessions for the current program_id
// Do something with program_sessions...
println!("Filtered program sessions for program id {}: {:?}", program_id, program_sessions);
}
}
}