From 0e6fdc0c5c64086aeb44dfb3e6cfa6dc727cde76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Sat, 28 Dec 2019 17:27:48 +0100 Subject: [PATCH] improve null handling --- src/lib.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index d7d74c6..ed2c9f1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -128,6 +128,7 @@ impl DotPaths for serde_json::Value { match self { Value::Array(vec) => vec.dot_get(path), Value::Object(map) => map.dot_get(path), + Value::Null => None, _ => { if path.is_empty() { serde_json::from_value(self.to_owned()).ok() @@ -142,6 +143,7 @@ impl DotPaths for serde_json::Value { match self { Value::Array(vec) => vec.dot_get_mut(path), Value::Object(map) => map.dot_get_mut(path), + Value::Null => None, _ => { if path.is_empty() { Some(self) @@ -227,6 +229,10 @@ fn new_by_path_root(path: &str, value: T) -> Value where T: Serialize, { + if path.is_empty() { + return serde_json::to_value(value).expect("Serialize error"); + } + let (sub1, _) = path_split(path); if sub1 == "0" || sub1 == "+" || sub1 == "<" || sub1 == ">" { // new vec @@ -548,6 +554,31 @@ mod tests { let _ = value.dot_get::("1.2.3"); } + #[test] + fn set_null() { + let mut item = Value::Null; + item.dot_set("", "foo"); + assert_eq!(Value::String("foo".into()), item); + } + + #[test] + fn replace_null() { + let mut item = Value::Null; + assert_eq!(None, item.dot_replace::<_, Value>("", "foo")); + assert_eq!(Value::String("foo".into()), item); + } + + #[test] + fn take_null() { + let mut item = Value::Null; + assert_eq!(None, item.dot_take::("")); + assert_eq!(Value::Null, item); + + let mut item = Value::Bool(true); + assert_eq!(Some(true), item.dot_take::("")); + assert_eq!(Value::Null, item); + } + #[test] fn set_vec() { let mut vec = Value::Array(vec![]);