1use serde::Serialize;
5use serde_json::ser::PrettyFormatter;
6use serde_json::Serializer;
7use tribufu_error::Result;
8
9#[macro_export]
10macro_rules! include_json {
11 ($path:expr) => {
12 $crate::from_str(include_str!($path)).expect("Failed to load JSON")
13 };
14}
15
16pub use serde_json::from_slice;
17pub use serde_json::from_str;
18pub use serde_json::to_string;
19pub use serde_json::to_value;
20pub use serde_json::to_vec_pretty;
21
22pub fn to_string_pretty<T>(value: &T) -> Result<String>
23where
24 T: Serialize,
25{
26 let obj = to_value(value).expect("Failed to serialize JSON");
27 let mut buf = Vec::new();
28 let fmt = PrettyFormatter::with_indent(b" ");
29 let mut ser = Serializer::with_formatter(&mut buf, fmt);
30 obj.serialize(&mut ser)?;
31 Ok(String::from_utf8(buf)?)
32}
33
34#[cfg(test)]
35mod tests {
36 use super::*;
37 use serde::{Deserialize, Serialize};
38
39 #[derive(Debug, Serialize, Deserialize)]
40 struct JsonTest {
41 version: String,
42 }
43
44 #[test]
45 fn test_include_json() {
46 let data: JsonTest = include_json!("test.json");
47 assert!(data.version == "0.0.0".to_owned())
48 }
49}