swaggest / json-diff

JSON diff/rearrange/patch/pointer library for PHP
MIT License
220 stars 30 forks source link

Remove last elemnt followed by add converting to associative array #31

Closed blake-stoker closed 4 years ago

blake-stoker commented 4 years ago

Removing the last element of an array by index followed by adding a new element converts the object to an associative array with numeric indices.

This patch

[
  {"op":"add","path":"","value":["a","b","c","d"]},
  {"op":"remove","path":"\/3"},
  {"op":"add","path":"\/-","value":"e"}
]

should produce (an array)

[
  "a",
  "b",
  "c",
  "e"
]

but does produce (an object)

{
  "0":"a",
  "1":"b",
  "2":"c",
  "4":"e"
}

php code snipit

$reportData = json_decode('{}');
$patch = JsonPatch::import(json_decode('[{"op":"add","path":"","value":["a","b","c","d"]},{"op":"remove","path":"\/3","value":""},{"op":"add","path":"\/-","value":"e"}]'));
$patch->apply($reportData);

print(json_encode($reportData));

If the last element is removed

[
  "op":"remove",
  "path":"\/4"
]

the output object becomes an array again.
This holds true for however many elements are added (ie add 10, remove 1, and the object is an array again).

vearutop commented 4 years ago

Fixed in v3.7.5, thank you for reporting. :+1: