Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created July 26, 2023 06:40
Show Gist options
  • Save matthewjberger/ece7809c18c68aff63251b44fe976d9a to your computer and use it in GitHub Desktop.
Save matthewjberger/ece7809c18c68aff63251b44fe976d9a to your computer and use it in GitHub Desktop.
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