jsonpatch adding element to array and creating it if not exist

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>

Tags:

Json Patch