jsonpatch adding element to array and creating it if not exist
Asked Answered
D

2

14

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?

Disclamation answered 6/12, 2017 at 9:0 Comment(3)
Your patch is perfectly right. You can try it here: json8.github.io/patch/demos/applyAperture
Maybe my question is not detailed enough. My example is working but the result is not what i need. This is a working example for adding one element to another: jsfiddle.net/s22ksqf8 but this is not working if the source document is empty. And if you use my second example (jsfiddle.net/67xLty9n) only the added item will be in the result documentDisclamation
Oh I misread your question. You can't do this in a pure patch, you'll need some logic in your JS. I'll write an answer.Aperture
A
7

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>
Aperture answered 30/1, 2018 at 10:42 Comment(2)
ok is use a solution like this currently. I hoped there is a direct way to do this. But thanks for your replyDisclamation
@Omar Alshaker I feel like this lib could help a lot of people with a little better documentation. Please add some, apart from that it's a really good package.Entebbe
N
-1

At Openshift you can do this using command:

oc patch dc/NAME_OF_DC --type=json --patch '
[
  { 
    "op": "add",
    "path": "/spec/template/spec/containers/0/env/-",
    "value": {
      "name": "KUBERNETES_NAMESPACE",
      "valueFrom": {
          "fieldRef": {
              "fieldPath": "metadata.namespace"
          }
      }
    }
  }
]
'

More you can find here

Newmown answered 23/10, 2019 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.