JSON Comparison

1.1.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `jsoncomparison.Compare` to check for differences between two JSON-like Python objects (dictionaries). It also includes an example of using `ignore_rules` to skip specific keys during comparison, which is useful for dynamic fields like timestamps. The `check` method returns a dictionary detailing the differences or `NO_DIFF` if the objects are identical based on the comparison rules.

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)

view raw JSON →