Starcounter-Jack / JSON-Patch

Lean and mean Javascript implementation of the JSON-Patch standard (RFC 6902). Update JSON documents using delta patches.
MIT License
1.82k stars 215 forks source link

Invalid patch is generated, when compared array has empty slots #218

Open maxlk opened 5 years ago

maxlk commented 5 years ago

According to RFC 6902, when add operation is used to insert a new value to an array:

The specified index MUST NOT be greater than the number of elements in the array.

This requirement is not fulfilled when array contains empty slots. For example

jsonpatch.compare(["a"], ["a",,"c"])

returns

[
  {
    "op": "add",
    "path": "/2",
    "value": "c"
  }
]

Which is not correct according to specification, since specified index 2 (from "path": "/2") is greater than the number of the elements in the array ["a"], which is 1.

It sounds reasonable to censore empty slots in array to null, to be aligned with JSON.stringify() behaviour. So, the example above should return:

[
  {
    "op": "add",
    "path": "/1",
    "value": null
  },
  {
    "op": "add",
    "path": "/2",
    "value": "c"
  }
]
abrad45 commented 5 years ago

This is biting me on my project, too. This repl.it demonstrates the issue https://repl.it/repls/BouncyInfantilePrograms which returns error OPERATION_VALUE_OUT_OF_BOUNDS

var compare = require('fast-json-patch').compare;
var validate = require('fast-json-patch').validate;

const ogData = {
    key: ['foo'],
};

const newData = {
    key: ['foo',,, 'bar'],
};

const patch = compare(ogData, newData);
console.log(patch, validate(patch, ogData));