#[derive(Clone, Debug, PartialEq)]
pub enum Json {
Null,
Bool(bool),
Number(f64),
Integer(i64),
String(String),
Array(Vec<Json>),
Object(Vec<(String, Json)>),
}
impl Json {
pub fn get(&self, key: &str) -> Option<&Self> {
match self {
Self::Object(entries) => entries.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
}
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Self::Number(n) => Some(*n),
Self::Integer(i) => Some(*i as f64),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Self::Integer(i) => Some(*i),
_ => self
.as_f64()
.filter(|n| n.fract() == 0.0 && n.abs() < 9.0e15)
.map(|n| n as i64),
}
}
pub fn is_integer(&self) -> bool {
matches!(self, Self::Integer(_))
}
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(s) => Some(s),
_ => None,
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(b) => Some(*b),
_ => None,
}
}
pub fn as_array(&self) -> Option<&[Self]> {
match self {
Self::Array(items) => Some(items),
_ => None,
}
}
pub fn as_object(&self) -> Option<&[(String, Self)]> {
match self {
Self::Object(entries) => Some(entries),
_ => None,
}
}
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
pub fn as_f64_vec(&self) -> Option<Vec<f64>> {
self.as_array()?.iter().map(Self::as_f64).collect()
}
}
impl From<f64> for Json {
fn from(n: f64) -> Self {
Self::Number(n)
}
}
impl From<bool> for Json {
fn from(b: bool) -> Self {
Self::Bool(b)
}
}
impl From<&str> for Json {
fn from(s: &str) -> Self {
Self::String(s.to_owned())
}
}
impl From<String> for Json {
fn from(s: String) -> Self {
Self::String(s)
}
}
impl<T: Into<Self>> From<Vec<T>> for Json {
fn from(items: Vec<T>) -> Self {
Self::Array(items.into_iter().map(Into::into).collect())
}
}
impl<T: Into<Self>> From<Option<T>> for Json {
fn from(value: Option<T>) -> Self {
value.map_or(Self::Null, Into::into)
}
}