json.rs 943 B

123456789101112131415161718192021222324252627282930313233
  1. use std::{io::Read, path::Path};
  2. use anyhow::Context;
  3. pub(crate) fn minify_json(source: &str) -> anyhow::Result<String> {
  4. // First try to parse the json
  5. let json: serde_json::Value = serde_json::from_str(source)?;
  6. // Then print it in a minified format
  7. let json = serde_json::to_string(&json)?;
  8. Ok(json)
  9. }
  10. pub(crate) fn process_json(source: &Path, output_path: &Path) -> anyhow::Result<()> {
  11. let mut source_file = std::fs::File::open(source)?;
  12. let mut source = String::new();
  13. source_file.read_to_string(&mut source)?;
  14. let json = match minify_json(&source) {
  15. Ok(json) => json,
  16. Err(err) => {
  17. tracing::error!("Failed to minify json: {}", err);
  18. source
  19. }
  20. };
  21. std::fs::write(output_path, json).with_context(|| {
  22. format!(
  23. "Failed to write json to output location: {}",
  24. output_path.display()
  25. )
  26. })?;
  27. Ok(())
  28. }