Created
July 26, 2023 06:40
-
-
Save matthewjberger/ece7809c18c68aff63251b44fe976d9a to your computer and use it in GitHub Desktop.
Lookup json fields in rust - https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b244a3aea4e73d5958b5527a21f0a51f
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde_json::Value; | |
fn get_value<'a>(j: &'a Value, p: &str) -> Option<&'a Value> { | |
let keys = p.split('/').collect::<Vec<&str>>(); | |
let mut current_value = j; | |
for key in keys { | |
current_value = match current_value.get(key) { | |
Some(value) => value, | |
None => return None, | |
}; | |
} | |
Some(current_value) | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
use serde_json::json; | |
#[test] | |
fn test_get_value() { | |
let data = json!({ | |
"user": { | |
"name": "John Cena", | |
"age": 40, | |
"addresses": { | |
"home": { | |
"street": "123 Sesame St", | |
} | |
} | |
} | |
}); | |
assert_eq!(get_value(&data, "user/name"), Some(&json!("John Cena"))); | |
assert_eq!(get_value(&data, "user/age"), Some(&json!(40))); | |
assert_eq!( | |
get_value(&data, "user/addresses/home/street"), | |
Some(&json!("123 Sesame St")) | |
); | |
assert_eq!(get_value(&data, "user/addresses/home/zip"), None); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment