Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One solution is to parse the JSON into a serdejson::Value and then use the asserteq! macro to compare the values recursively.

For example:

use serde_json::json;

#[test]
fn test_json() {
    let expected = json!({
        "name": "Alice",
        "age": 30,
        "address": {
            "street": "123 Main St",
            "city": "Seattle"
        },
        "phones": ["555-1234", "555-5678"]
    });

    let actual = json!({
        "name": "Alice",
        "age": 30,
        "phones": ["555-5678", "555-1234"], // Keys reordered
        "address": {
            "city": "Seattle",
            "street": "123 Main St" // Keys reordered
        }
    });

    assert_eq!(expected, actual); // Fails because of key order

    assert_eq!(
        serde_json::to_value(expected).unwrap(),
        serde_json::to_value(actual).unwrap()
    ); // Succeeds because keys are ignored
}

In this example, the expected and actual JSON objects have the same keys and values, but the order is different for some of the objects. Therefore, the first asserteq! macro would fail. However, by converting the objects into serdejson::Value and testing for equality, the keys are ignored and the test passes.