Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsonpatch adding element to array and creating it if not exist

Tags:

json-patch

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?

like image 349
nblum Avatar asked Dec 06 '17 09:12

nblum


1 Answers

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>
like image 139
Omar Alshaker Avatar answered Oct 15 '22 23:10

Omar Alshaker