JSON Comparison
The `jsoncomparison` package is a Python utility designed to compare two objects with a JSON-like structure and data types. It provides a flexible way to identify differences between expected and actual JSON objects, making it suitable for tasks like API testing and configuration validation. The library is currently active, with its latest stable version being 1.1.0.
Warnings
- gotcha By default, `jsoncomparison` checks for both value and type equality. A common footgun is comparing a numeric value (e.g., `1`) in one JSON object with a string representation of the same number (e.g., `'1'`) in another. This will be flagged as a type mismatch, even if the values appear numerically equivalent.
- gotcha The library's comparison is order-sensitive for arrays by default. If the order of elements within an array does not matter for your use case, `jsoncomparison` will report differences if the order varies. This is a common pitfall in JSON comparison generally.
- gotcha When comparing JSON objects that contain dynamic fields (e.g., timestamps, auto-generated IDs, or fields whose values are expected to change frequently but are not critical for comparison), these will always be reported as differences. Failing to account for them can lead to flaky tests or cluttered difference reports.
- gotcha By default, `jsoncomparison`'s configuration typically does not print the comparison result directly to the console; instead, it writes results to a file. Users expecting immediate console output during debugging might miss this default behavior.
Install
-
pip install jsoncomparison
Imports
- Compare
from jsoncomparison import Compare
- NO_DIFF
from jsoncomparison import NO_DIFF
Quickstart
from jsoncomparison import Compare, NO_DIFF
expected = {
"project": {
"name": "jsoncomparison",
"version": "0.1",
"license": "MIT",
"language": {
"name": "python",
"versions": [3.5, 3.6]
}
},
"os": "linux"
}
actual = {
"project": {
"name": "jsoncomparison",
"version": 0.1, # Intentional type mismatch for demonstration
"license": "Apache 2.0",
"language": {
"name": "python",
"versions": [3.6]
}
}
}
# Perform comparison
diff = Compare().check(expected, actual)
# Check if differences exist
if diff != NO_DIFF:
print("Differences found:")
print(diff)
else:
print("No differences found.")
# Example with ignore rules for dynamic fields or irrelevant keys
expected_with_dynamic = {"id": 1, "timestamp": "2023-01-01T12:00:00Z", "data": {"value": 10}}
actual_with_dynamic = {"id": 1, "timestamp": "2023-01-02T10:30:00Z", "data": {"value": 10}}
# Ignore 'timestamp' field
compare_with_ignore = Compare(ignore_rules={'timestamp'}).check(expected_with_dynamic, actual_with_dynamic)
if compare_with_ignore == NO_DIFF:
print("\nNo differences found after ignoring 'timestamp'.")
else:
print("\nDifferences found even after ignoring 'timestamp':")
print(compare_with_ignore)