1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use na::{Dim, Matrix, Scalar};
use serde::Serialize;
use serde_json::{to_string, Value};

/// Write JSON string to file.
pub fn write_str<S: AsRef<str>>(path: S, string: String) {
    std::fs::write(path.as_ref(), string).unwrap();
}

/// Convert matrix to json.
pub fn matrix_to_json<N, R, C, S>(matrix: &Matrix<N, R, C, S>) -> Value
where
    N: Scalar,
    R: Dim,
    C: Dim,
    S: Serialize,
{
    serde_json::from_str(&to_string(matrix).unwrap()).unwrap()
}

/// Add **kwargs to json map.
#[macro_export]
macro_rules! addjs {
    ($map:expr, $(($key:expr, $value:expr)), *) => {{
        use serde_json::{from_str, to_string_pretty};
        $(
            let json_value = from_str(&to_string_pretty(&$value).unwrap()).unwrap();
            $map[$key] = json_value;
        )*
        $map
    }}
}

/// Create new json map from **kwargs.
#[macro_export]
macro_rules! newjs {
    ($(($key:expr, $value:expr)), *) => {{
        use serde_json::json;
        let mut map = json!({});
        $crate::addjs!(&mut map, $(($key, $value)), *);
        map
    }}
}

/// Write json map to file.
#[macro_export]
macro_rules! writejs {
    ($path:expr, $json:expr) => {
        use serde_json::to_string_pretty;
        use std::fs;
        let json_string = to_string_pretty(&$json).unwrap();
        fs::write($path, json_string).unwrap();
    };
}