jsonpatch adding element to array and creating it if not exist

nblum picture nblum · Dec 6, 2017 · Viewed 15.1k times · Source

I'm trying to append an element to an array. But i cannot ensure that the array alread exists. So it should be created if not.

This example works:

Source json:

{
  "data": []
}

Patch doc:

[{
  "op":"add",
  "path":"/data/-",
  "value": "foo"
}]

But in this case it will not append anything:

Source json:

{}

I tried a solution by adding first an empty array and then appending, but this will always clear existing entries:

[{
  "op":"add",
  "path":"/scores",
  "value": []
}, 
{
  "op":"add",
  "path":"/scores/-",
  "value": {
    "time":1512545873
    }
}]

Have i missed something or is there no solution for this in the spec?

Answer

Omar Alshaker picture Omar Alshaker · Jan 30, 2018

It's nice to you see you using fast-json-patch. I maintain this lib.

I would say you can't acheive this by pure JSON patches. You'll need some logic in your JS. Like the following:

var doc = {};

var patch = [{
  "op": "add",
  "path": "/scores/-",
  "value": {
    "time": 456
  }
}];

var arr = jsonpatch.getValueByPointer(doc, '/scores');
if (!arr) {
  jsonpatch.applyOperation(doc, {
    "op": "add",
    "path": "/scores",
    "value": []
  });
}

var out = jsonpatch.applyPatch(doc, patch).newDocument;
pre.innerHTML = JSON.stringify(out);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fast-json-patch/2.0.6/fast-json-patch.min.js"></script>

<pre id="pre"></pre>