json-diff icon indicating copy to clipboard operation
json-diff copied to clipboard

RFC incompatibility when adding item to an array

Open tg666 opened this issue 4 months ago • 0 comments

When an item is added to an existing index, the result should be only an add operation on that index. Instead, the patch contains a series of replace operations and an add operation for the last item, which was moved to an index that did not previously exist.

use Swaggest\JsonDiff\JsonDiff;
use Swaggest\JsonDiff\JsonPatch;

$original = (object) [
    "items" => ["a", "b", "c"],
];

$modified = (object) [
    "items" => ["a", "x", "b", "c"],
];

$jsonDiff = new JsonDiff(
    original: $original,
    new: $modified,
);

echo json_encode(JsonPatch::export($jsonDiff->getPatch()), JSON_PRETTY_PRINT);

The current result:

[
    {
        "op": "replace",
        "path": "/items/1",
        "value": "x"
    },
    {
        "op": "replace",
        "path": "/items/2",
        "value": "b"
    },
    {
        "op": "add",
        "path": "/items/3",
        "value": "c"
    }
]

The expected result:

[
    { 
        "op": "add", 
        "path": "/items/1",
        "value": "x"
     }
]

tg666 avatar Sep 12 '25 05:09 tg666