Skip to content

Commit

Permalink
Merge pull request 1069 from chanced/add-as_number-to-value
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Sep 9, 2023
2 parents 6525ffa + cf433e9 commit c308779
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,29 @@ impl Value {
}
}

/// If the `Value` is an Number, returns the associated [`Number`]. Returns None
/// otherwise.
///
/// ```
/// # use serde_json::{json, Number};
/// #
/// let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" });
///
/// assert_eq!(v["a"].as_number(), Some(&Number::from(1u64)));
/// assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap()));
/// assert_eq!(v["c"].as_number(), Some(&Number::from(-3i64)));
///
/// // The string `"4"` is not a number.
/// assert_eq!(v["d"].as_number(), None);
///
/// ```
pub fn as_number(&self) -> Option<&Number> {
match self {
Value::Number(number) => Some(number),
_ => None,
}
}

/// Returns true if the `Value` is a Number. Returns false otherwise.
///
/// ```
Expand Down

0 comments on commit c308779

Please sign in to comment.