diff --git a/src/json/value.rs b/src/json/value.rs index bfec0474..03e41df8 100644 --- a/src/json/value.rs +++ b/src/json/value.rs @@ -46,6 +46,22 @@ impl Value { 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::>(); + self.find_path(&paths) + } + /// 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 /// or the `Value` is not an Object, returns None. diff --git a/tests/test_json.rs b/tests/test_json.rs index f6ca5a47..48920a87 100644 --- a/tests/test_json.rs +++ b/tests/test_json.rs @@ -1065,3 +1065,12 @@ fn test_missing_fmt_renamed_field() { ))).unwrap(); 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()); +}