Skip to content

Commit a55ec8a

Browse files
committed
Do not unwrap on bad json files
1 parent b83d74e commit a55ec8a

File tree

1 file changed

+21
-19
lines changed
  • json-structural-diff-cli/src

1 file changed

+21
-19
lines changed

json-structural-diff-cli/src/main.rs

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ use std::process;
99
use clap::{App, Arg};
1010
use console::Term;
1111
use rayon::prelude::*;
12-
use serde_json::Value;
1312
use walkdir::{DirEntry, WalkDir};
1413

1514
use json_structural_diff::{colorize, JsonDiff};
@@ -27,25 +26,28 @@ fn act_on_file(
2726
cfg: &Config,
2827
) -> std::io::Result<()> {
2928
let buffer1 = std::fs::read(&path1).unwrap();
30-
let json1: Value = serde_json::from_slice(&buffer1).unwrap();
3129
let buffer2 = std::fs::read(path2).unwrap();
32-
let json2: Value = serde_json::from_slice(&buffer2).unwrap();
33-
34-
if json1 != json2 {
35-
let json_diff = JsonDiff::diff(&json1, &json2, cfg.only_keys);
36-
let result = json_diff.diff.unwrap();
37-
let json_string = if cfg.raw {
38-
serde_json::to_string_pretty(&result)?
39-
} else {
40-
colorize(&result, cfg.color)
41-
};
42-
if let Some(output_path) = output_path {
43-
let output_filename = path1.file_name().unwrap().to_str().unwrap();
44-
let mut output_file = File::create(output_path.join(output_filename))?;
45-
writeln!(&mut output_file, "{}", json_string)?;
46-
} else {
47-
let mut term = Term::stdout();
48-
term.write_all(json_string.as_bytes())?;
30+
31+
if let (Ok(json1), Ok(json2)) = (
32+
serde_json::from_slice(&buffer1),
33+
serde_json::from_slice(&buffer2),
34+
) {
35+
if json1 != json2 {
36+
let json_diff = JsonDiff::diff(&json1, &json2, cfg.only_keys);
37+
let result = json_diff.diff.unwrap();
38+
let json_string = if cfg.raw {
39+
serde_json::to_string_pretty(&result)?
40+
} else {
41+
colorize(&result, cfg.color)
42+
};
43+
if let Some(output_path) = output_path {
44+
let output_filename = path1.file_name().unwrap().to_str().unwrap();
45+
let mut output_file = File::create(output_path.join(output_filename))?;
46+
writeln!(&mut output_file, "{}", json_string)?;
47+
} else {
48+
let mut term = Term::stdout();
49+
term.write_all(json_string.as_bytes())?;
50+
}
4951
}
5052
}
5153
Ok(())

0 commit comments

Comments
 (0)