Merge pull request #76 from blaenk/json-lookup

implement lookup method for json::Value
This commit is contained in:
Erick Tryzelaar 2015-05-18 21:50:55 -07:00
commit 5fe85128c2
2 changed files with 25 additions and 0 deletions

View File

@ -46,6 +46,22 @@ impl Value {
Some(target) Some(target)
} }
/// Looks up a value by path.
///
/// This is a convenience method that splits the path by `'.'`
/// and then feeds the sequence of keys into the `find_path`
/// method.
///
/// ``` ignore
/// let obj: Value = json::from_str(r#"{"x": {"a": 1}}"#).unwrap();
///
/// assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
/// ```
pub fn lookup<'a>(&'a self, path: &'a str) -> Option<&'a Value> {
let paths = path.split('.').collect::<Vec<&str>>();
self.find_path(&paths)
}
/// If the `Value` is an Object, performs a depth-first search until /// If the `Value` is an Object, performs a depth-first search until
/// a value associated with the provided key is found. If no value is found /// a value associated with the provided key is found. If no value is found
/// or the `Value` is not an Object, returns None. /// or the `Value` is not an Object, returns None.

View File

@ -1065,3 +1065,12 @@ fn test_missing_fmt_renamed_field() {
))).unwrap(); ))).unwrap();
assert_eq!(value, Foo { x: Some(5) }); assert_eq!(value, Foo { x: Some(5) });
} }
#[test]
fn test_lookup() {
let obj: Value = json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
assert!(obj.lookup("y").unwrap() == &Value::U64(2));
assert!(obj.lookup("z").is_none());
}