Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds as_number to Value #1069

Merged
merged 3 commits into from
Sep 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,34 @@ 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" });
///
/// // The number `1` is an u64.
/// assert_eq!(v["a"].as_number(), Some(&Number::from(1u64)));
///
/// // The number `2.2` is an f64.
/// assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap()));
///
/// // The number `-3` is an i64.
/// 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