compare-json (Python)
compare-json-py is the Python port of compare-json — structured JSON comparison with the same semantics as the engine that powers this website. It detects additions, deletions, type changes, and value changes between two JSON values, with control over how keys, values, and arrays are matched. Ships as both a library and a CLI, with zero runtime dependencies.
Language: Python — distributed via PyPI. Source code on GitHub.
Installation
pip install compare-json-py
Quick Start
Library
from compare_json import compareJSON, CompareOptions
base = {"name": "Alice", "age": 30}
contrast = {"name": "Bob", "age": "30", "email": "[email protected]"}
diffs = compareJSON(base, contrast)
for d in diffs:
print(d.path_string, d.path_belongs_to, d.diff_type.value)
# name both valueChanged
# age both typeChanged
# email contrast added
# With options
options = CompareOptions(
array_compare_method="lcs", # or "byIndex", "unordered"
key_case_insensitive=True,
value_case_insensitive=True,
numeric_string_equals_number=True,
)
diffs = compareJSON(base, contrast, options)
CLI
# Compare JSON files
compare-json base.json contrast.json
# Compare inline JSON strings
compare-json '{"a":1}' '{"a":2,"b":3}'
# Array strategies and case-insensitive matching
compare-json base.json contrast.json -a lcs -k -v
# Machine-readable JSON output
compare-json base.json contrast.json -j
# Write the report to a file
compare-json base.json contrast.json -o diff.txt
Options
| Flag | Description |
|---|---|
-a, --array-compare-method | Array comparison strategy: byIndex (default), lcs, unordered |
-k, --key-case-insensitive | Compare object keys case-insensitively |
-v, --value-case-insensitive | Compare string values case-insensitively |
--numeric-string-equals-number | Treat numeric strings as equal to numbers |
-j, --json-export | Output the differences as JSON |
-o, --output FILE | Write output to a file instead of stdout |
See Comparison Options and Array Comparison Methods for what each setting does.
License
MIT