| Crates.io | serde-json-assert |
| lib.rs | serde-json-assert |
| version | 0.4.0 |
| created_at | 2025-02-28 22:26:14.624868+00 |
| updated_at | 2025-06-13 11:27:45.773923+00 |
| description | Flexible JSON assertions |
| homepage | https://github.com/hardselius/serde-json-assert |
| repository | https://github.com/hardselius/serde-json-assert |
| max_upload_size | |
| id | 1573267 |
| size | 99,445 |
This crate is a fork of davidpederson/assert-json-diff. It expands on the functionality to provide an even more flexible tool for JSON testing.
This crate includes macros for comparing two serializable values by diffing their JSON
representations. It is designed to give much more helpful error messages than the standard
assert_eq!. It basically does a diff of the two objects and tells you the exact
differences. This is useful when asserting that two large JSON objects are the same.
It uses the serde and serde_json to perform the serialization.
If you want to assert that one JSON value is "included" in another use
assert_json_include:
use serde_json_assert::assert_json_include;
use serde_json::json;
let a = json!({
"data": {
"users": [
{
"id": 1,
"country": {
"name": "Denmark"
}
},
{
"id": 24,
"country": {
"name": "Denmark"
}
}
]
}
});
let b = json!({
"data": {
"users": [
{
"id": 1,
"country": {
"name": "Sweden"
}
},
{
"id": 2,
"country": {
"name": "Denmark"
}
}
]
}
});
assert_json_include!(actual: a, expected: b)
This will panic with the error message:
json atoms at path ".data.users[0].country.name" are not equal:
expected:
"Sweden"
actual:
"Denmark"
json atoms at path ".data.users[1].id" are not equal:
expected:
2
actual:
24
assert_json_include allows extra data in
actual but not in expected. That is so you can verify just a part of the
JSON without having to specify the whole thing. For example this test passes:
use serde_json_assert::assert_json_include;
use serde_json::json;
assert_json_include!(
actual: json!({
"a": { "b": 1 },
}),
expected: json!({
"a": {},
})
)
However expected cannot contain additional data so this test fails:
use serde_json_assert::assert_json_include;
use serde_json::json;
assert_json_include!(
actual: json!({
"a": {},
}),
expected: json!({
"a": { "b": 1 },
})
)
That will print
json atom at path ".a.b" is missing from actual
If you want to ensure two JSON values are exactly the same, use
assert_json_eq.
use serde_json_assert::assert_json_eq;
use serde_json::json;
assert_json_eq!(
json!({ "a": { "b": 1 } }),
json!({ "a": {} })
)
This will panic with the error message:
json atom at path ".a.b" is missing from lhs
You can use [assert_json_matches] to further customize the comparison.
This contribution is dual licensed under EITHER OF
in addition to the original license of the assert-json-diff crate.