From ee6dc9a076dedcf3586e16b651192936f3450acf Mon Sep 17 00:00:00 2001 From: Luis Alberto Santos Date: Wed, 6 Nov 2024 17:41:52 +0100 Subject: [PATCH] added consuming variants of the 'as_...' methods --- src/value/mod.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/src/value/mod.rs b/src/value/mod.rs index 6b40f9a52..b71619351 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -388,6 +388,24 @@ impl Value { } } + /// If the `Value` is an Object, returns the associated Map consuming it. + /// Returns None otherwise. + /// + /// ``` + /// # use serde_json::json; + /// # + /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] }); + /// + /// // The length of `{"nested": true}` is 1 entry. + /// assert_eq!(v["a"].into_object().unwrap().len(), 1); + /// ``` + pub fn into_object(self) -> Option> { + match self { + Value::Object(map) => Some(map), + _ => None, + } + } + /// Returns true if the `Value` is an Array. Returns false otherwise. /// /// For any Value on which `is_array` returns true, `as_array` and @@ -447,6 +465,24 @@ impl Value { } } + /// If the `Value` is an Array, returns the associated vector consuming it. + /// Returns None otherwise. + /// + /// ``` + /// # use serde_json::json; + /// # + /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } }); + /// + /// // The length of `["an", "array"]` is 2 elements. + /// assert_eq!(v["a"].into_array().unwrap().len(), 2); + /// ``` + pub fn into_array(self) -> Option> { + match self { + Value::Array(array) => Some(array), + _ => None, + } + } + /// Returns true if the `Value` is a String. Returns false otherwise. /// /// For any Value on which `is_string` returns true, `as_str` is guaranteed @@ -496,6 +532,23 @@ impl Value { } } + /// If the `Value` is a String, returns the associated String consuming it. + /// Returns None otherwise. + /// + /// ``` + /// # use serde_json::json; + /// # + /// let v = json!({ "a": "some string", "b": false }); + /// + /// assert_eq!(v["a"].into_string().unwrap(), "some string"); + /// ``` + pub fn into_string(self) -> Option { + match self { + Value::String(s) => Some(s), + _ => None, + } + } + /// Returns true if the `Value` is a Number. Returns false otherwise. /// /// ``` @@ -537,6 +590,23 @@ impl Value { } } + /// If the `Value` is a Number, returns the associated [`Number`] consuming it. + /// Returns None otherwise. + /// + /// ``` + /// # use serde_json::{json, Number}; + /// # + /// let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" }); + /// + /// assert_eq!(v["a"].into_number(), Some(Number::from(1u64))); + /// ``` + pub fn into_number(self) -> Option { + match self { + Value::Number(number) => Some(number), + _ => None, + } + } + /// Returns true if the `Value` is an integer between `i64::MIN` and /// `i64::MAX`. ///