Skip to content

Add is_empty method for Value #1283

@decadenza

Description

@decadenza

At application level, it is often useful to check if a value is empty, in the broader sense, i.e. if it is null, "", [], or {}.

Is there any particular reason why there is no general is_empty method for Value?
Is this simple addition worth considering?

For example:

/// A trait of [serde_json::Value] to check if it is empty.
pub trait IsEmpty {
    /// Check if the value is empty.
    fn is_empty(&self) -> bool;
}

impl IsEmpty for Value {
    fn is_empty(&self) -> bool {
        match self {
            Value::Null => true, // This may be a stretch, but in practice I often don't want to deal with a null.
            Value::String(s) if s.is_empty() => true, // These just call the underlying ones...
            Value::Array(a) if a.is_empty() => true,
            Value::Object(o) if o.is_empty() => true,
            _ => false,
        }
    }
}

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions