home ~ projects ~ socials

Compare Two JSON Strings in Rust

Do They Match?

This is how I'm comparing two json strings in Rust:

---
[dependencies]
anyhow = "1.0.98"
serde_json = "1.0.140"
---

use anyhow::Result;
use serde_json::Value;

fn json_matches(a: &str, b: &str) -> Result<bool> {
  let a_json: Value = serde_json::from_str(a)?;
  let b_json: Value = serde_json::from_str(b)?;
  if a_json == b_json {
    Ok(true)
  } else {
    Ok(false)
  }
}

fn main() -> Result<()> {
  let string_one = 
    r#"{ "alfa": "bravo" }"#;

  let string_two = 
    r#"{ "alfa": "bravo" }"#;

  let string_three = 
    r#"{ "alfa": "charlie" }"#;

  let one_and_two_match = json_matches(
    &string_one, &string_two
  )?;

  let one_and_three_match = json_matches(
    &string_one, &string_three
  )?;

  println!(
    "one and two match: {}", one_and_two_match
  );

  println!(
    "one and three match: {}", one_and_three_match
  );

  Ok(())
}
Output:
one and two match: true
one and three match: false

Notes

  • The json_matches() function does the comparison.
  • It returns true or false wrapped in a Result.
  • If either one of the JSON strings can't be parsed the Result is an Error.
  • If they both parse, the comparison is made.
  • The order of the keys in the JSON Object doesn't matter. For example, these match even though the order is different:

    { "charlie": "delta", "alfa": "bravo" }
    { "alfa": "bravo", "charlie": "delta" }
  • I'm using anyhow for error handling. That's not required. It's just what I find easiest to deal with.

Comparison Testing

The impetus behind this post was setting up a way to get the output of the Neopolitan parser. It's working great for that.

-a

-- end of line --