Search code examples
rustserde

In Rust tests, how to assert_eq some json that keeps reordering its keys


My Rust lib does some operations on JSON, and in unit tests I need to ensure the correctness of the lib. Yet, json to string conversion keeps key order unstable. I do NOT want to modify the lib to include json sorting, but I do need to compare the results effectively in my unit tests. What can I do to simplify this comparison?


Solution

  • The simplest answer would be to parse both strings and compare the parsed values for equality. This compares the strings semantically instead of literally, which is what you want anyway. Aside from key order, other non-semantic differences in the strings (like amounts of insignificant whitespace or escaped vs unescaped characters) will also be ignored.

    assert_eq!(
        a.parse::<serde_json::Value>().unwrap(),
        b.parse::<serde_json::Value>().unwrap()
    );
    

    If your library itself doesn't depend on serde_json, you can include it as a dev dependency to have it available during tests without requiring users of your library to depend on it transitively.