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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With