#![cfg_attr(docsrs, feature(doc_cfg))]
extern crate self as wang_utils_json;
use serde::Serialize;
use std::fs;
use std::path::Path;
pub fn write_json_to_file<P: AsRef<Path>, T>(path: P, value: &T) -> anyhow::Result<()>
where
T: ?Sized + Serialize,
{
let result = serde_json::to_string(value)?;
fs::write(path, result)?;
Ok(())
}
pub fn write_pretty_json_to_file<P: AsRef<Path>, T>(path: P, value: &T) -> anyhow::Result<()>
where
T: ?Sized + Serialize,
{
let result = serde_json::to_string_pretty(value)?;
fs::write(path, result)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_write_json_to_file() -> anyhow::Result<()> {
let json = json!({
"user":"123312",
"pwd":"user-pwd"
});
println!("{:#?}", json);
write_pretty_json_to_file("test.json", &json)?;
fs::remove_file("test.json")?;
Ok(())
}
}