use serde_json::Value;
pub(crate) fn is_truthy(value: &Value) -> bool {
match value {
Value::Null => false,
Value::Bool(value) => *value,
Value::Number(number) => number.as_f64() != Some(0.0),
Value::String(text) => !text.is_empty(),
Value::Array(items) => !items.is_empty(),
Value::Object(map) => !map.is_empty(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn empty_values_are_falsy() {
for value in [
json!(null),
json!(false),
json!(0),
json!(""),
json!([]),
json!({}),
] {
assert!(!is_truthy(&value), "{value} should be falsy");
}
}
#[test]
fn non_empty_values_are_truthy() {
for value in [
json!(true),
json!(1),
json!(-1),
json!("x"),
json!([0]),
json!({"a": 1}),
] {
assert!(is_truthy(&value), "{value} should be truthy");
}
}
}