Skip to content

adds as_number to Value#1069

Merged
dtolnay merged 3 commits intoserde-rs:masterfrom
chanced:add-as_number-to-value
Sep 9, 2023
Merged

adds as_number to Value#1069
dtolnay merged 3 commits intoserde-rs:masterfrom
chanced:add-as_number-to-value

Conversation

@chanced
Copy link
Copy Markdown
Contributor

@chanced chanced commented Sep 7, 2023

Resolves #1068 by adding as_number to Value.

@chanced
Copy link
Copy Markdown
Contributor Author

chanced commented Sep 7, 2023

/// 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,
    }
}

Copy link
Copy Markdown
Member

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@dtolnay dtolnay merged commit c308779 into serde-rs:master Sep 9, 2023
@chanced
Copy link
Copy Markdown
Contributor Author

chanced commented Sep 9, 2023

woops, I just realized I made 2 copypasta mistakes in the comment.

  • "an Number" should be "a Number.
  • "The number 1 is an u64." should be "The number 1 is a u64"

I'm sorry about not catching it sooner!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

It'd be useful if Value had an as_number method

2 participants