I have the JSON data below and I need to parse it using Rust. Using serde, I can access some of the JSON as such:
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();
But how do I filter for a single programData array item using the programs.id value? I'm trying something like this but I can't get it right:
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
}
]
}
}
If you wanna filter for a single
programDataarray item usingprogram.idyou need to change a couple things. Looks like you're directly comparing aserde_json::Valuewith anothoerserde_json::Valuewithin a nested structure which can lead to issues. You're also trying to filer onprogramDataas if it's a single object when it's actually an array.You should loop through each program, then for each program loop through each session then in each session filter
programDataitemas based onprogramRefId.Rust Playground Link
Filtered program sessions for program id 3: [Object {"dataPhase": Number(2), "programRefId": Number(3), "programSpecificData": Object {"completed": Bool(true)}}]