tool/core/
json.rs

1use na::{Dim, Matrix, Scalar};
2use serde::Serialize;
3use serde_json::{to_string, Value};
4
5/// Write JSON string to file.
6pub fn write_str<S: AsRef<str>>(path: S, string: String) {
7    std::fs::write(path.as_ref(), string).unwrap();
8}
9
10/// Convert matrix to json.
11pub fn matrix_to_json<N, R, C, S>(matrix: &Matrix<N, R, C, S>) -> Value
12where
13    N: Scalar,
14    R: Dim,
15    C: Dim,
16    S: Serialize,
17{
18    serde_json::from_str(&to_string(matrix).unwrap()).unwrap()
19}
20
21/// Add **kwargs to json map.
22#[macro_export]
23macro_rules! addjs {
24    ($map:expr, $(($key:expr, $value:expr)), *) => {{
25        use serde_json::{from_str, to_string_pretty};
26        $(
27            let json_value = from_str(&to_string_pretty(&$value).unwrap()).unwrap();
28            $map[$key] = json_value;
29        )*
30        $map
31    }}
32}
33
34/// Create new json map from **kwargs.
35#[macro_export]
36macro_rules! newjs {
37    ($(($key:expr, $value:expr)), *) => {{
38        use serde_json::json;
39        let mut map = json!({});
40        $crate::addjs!(&mut map, $(($key, $value)), *);
41        map
42    }}
43}
44
45/// Write json map to file.
46#[macro_export]
47macro_rules! writejs {
48    ($path:expr, $json:expr) => {
49        use serde_json::to_string_pretty;
50        use std::fs;
51        let json_string = to_string_pretty(&$json).unwrap();
52        fs::write($path, json_string).unwrap();
53    };
54}