swaggest/json-diff
PHP library for comparing and diffing JSON structures. Generate human-readable diffs and apply patches to reconcile documents, helping detect changes between API responses, configs, and data snapshots with support for nested objects and arrays.
Install via Composer: composer require swaggest/json-diff. Start by comparing two JSON-encoded arrays/objects — typically decoded with json_decode() — using the JsonDiff class. The simplest use case: detect what changed between a stored config version and a new one.
use Swaggest\JsonDiff\JsonDiff;
$old = json_decode('{"name": "Alice", "age": 30}', true);
$new = json_decode('{"name": "Alice", "age": 31, "active": true}', true);
$diff = JsonDiff::diff($old, $new);
// $diff contains patch structure (e.g., ['age' => [JsonDiff::OP_SET, 31], '+active' => true])
Apply the patch later with:
$restored = JsonDiff::patch($old, $diff);
// $restored === $new
Check the JsonDiff::OP_* constants for patch operation types (SET, ADD, REMOVE, etc.).
Integrate with Laravel by creating a service provider or trait:
trait Configurable
{
public function recordChange(array $old, array $new): void
{
$patch = JsonDiff::diff($old, $new);
JsonDiffLog::create(['entity' => $this, 'patch' => $patch]);
}
}
Use JsonDiff::diffPretty() for human-readable diffs in development/debug logs.
1 (int) vs "1" (string) produce a SET operation — ensure consistent encoding/decoding (e.g., use JSON_PRESERVE_ZERO_FRACTION or cast consistently).JsonDiff::OPT_SORT_ARRAYS or preprocess arrays with sort() before diffing.REMOVE op twice can fail or behave unexpectedly. Consider versioned patches or idempotent wrappers for stateful systems.JsonDiff to add custom operation types (e.g., JSON_DIFF_OP_MOVE) by extending the class and overriding buildOp().JsonDiff::getLastError() after operations to catch silent failures (e.g., malformed JSON input).How can I help you explore Laravel packages today?