boomack 0.4.1

Client library for Boomack
Documentation
//! Helpers for handling dynamic or extensible data structures
//! and converting them from and into JSON

pub type JVal = serde_json::Value;
pub type JMap<T> = serde_json::Map<String, T>;

pub type JsonMap = JMap<JVal>;

pub fn pprint_json<T>(x: &T) -> String
    where T: serde::Serialize
{
    serde_json::to_string_pretty(x).unwrap()
}

pub fn to_json_map<T>(x: &T) -> std::result::Result<JsonMap, Box<dyn std::error::Error>>
    where T: serde::Serialize
{
    let value = serde_json::to_value(x)?;
    if let JVal::Object(map) = value {
        std::result::Result::Ok(map)
    } else {
        panic!("Serialized object is no JSON map");
    }
}

pub fn set_json_value(map: &mut JsonMap, key: &str, value: JVal)
{
    map.insert(String::from(key), value);
}

pub fn set_json_str_value(map: &mut JsonMap, key: &str, value: &str)
{
    set_json_value(map, key, JVal::String(String::from(value)));
}

pub fn set_json_bool_value(map: &mut JsonMap, key: &str, value: bool)
{
    set_json_value(map, key, JVal::Bool(value));
}

pub fn f64_to_json(v: f64) -> Option<JVal> {
    serde_json::Number::from_f64(v).map(JVal::Number)
}

pub fn i64_to_json(v: i64) -> Option<JVal> {
    f64_to_json(v as f64)
}

pub fn f64_str_to_json(v: &str) -> Option<JVal> {
    v.parse::<f64>().ok().and_then(f64_to_json)
}

pub fn set_json_num_value(map: &mut JsonMap, key: &str, value: f64) {
    set_json_value(map, key, match serde_json::Number::from_f64(value) {
        Some(n) => JVal::Number(n),
        None => JVal::Null,
    });
}

pub fn set_json_obj_value(map: &mut JsonMap, key: &str, value: JsonMap) {
    set_json_value(map, key, JVal::Object(value));
}

pub fn set_json_arr_value(map: &mut JsonMap, key: &str, value: Vec<JVal>) {
    set_json_value(map, key, JVal::Array(value));
}

pub fn set_json_str_arr_value<I>(map: &mut JsonMap, key: &str, value: I)
    where I: IntoIterator, I::Item: AsRef<str>
{
    set_json_arr_value(map, key,
        value.into_iter().map(|x| JVal::String(String::from(x.as_ref()))).collect());
}