JSON Diff (mcepl/json_diff)

1.5.0 · maintenance · verified Thu Apr 16

The `json-diff` library (maintained by mcepl) provides a command-line tool to compare two JSON files and output their structural differences. While it was ported to Python 3 in its 1.5.0 release, its development has been inactive since 2019. It aims to identify additions, deletions, and modifications between JSON structures, generating a new JSON file or console output with the result. This library is considered to be in maintenance mode due to its age and lack of recent updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `json-diff` via its command-line interface, which is its primary mode of operation. It compares two temporary JSON files and outputs the differences to a third file.

import os
import json
import subprocess

# Create dummy JSON files for demonstration
json1_data = {"name": "Alice", "age": 30, "city": "New York"}
json2_data = {"name": "Alice", "age": 31, "occupation": "Engineer"}

file1 = "file1.json"
file2 = "file2.json"
output_file = "diff_output.json"

with open(file1, "w") as f:
    json.dump(json1_data, f, indent=2)
with open(file2, "w") as f:
    json.dump(json2_data, f, indent=2)

# Run json-diff as a command-line tool
try:
    # Using python -m to invoke the module as a script
    command = ["python", "-m", "json_diff.json_diff", file1, file2, "-o", output_file]
    result = subprocess.run(command, capture_output=True, text=True, check=True)

    print("json-diff output:")
    print(result.stdout)
    if result.stderr:
        print("json-diff errors:")
        print(result.stderr)

    with open(output_file, 'r') as f:
        diff_result = json.load(f)
        print(f"\nDifferences written to {output_file}:")
        print(json.dumps(diff_result, indent=2))

except subprocess.CalledProcessError as e:
    print(f"Error running json-diff: {e}")
    print(f"Stdout: {e.stdout}")
    print(f"Stderr: {e.stderr}")
except FileNotFoundError:
    print("Error: 'python' command not found. Ensure Python is in your PATH.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    # Clean up dummy files
    for f in [file1, file2, output_file]:
        if os.path.exists(f):
            os.remove(f)

view raw JSON →