0

I have been reading about JSON Patch. However, I cannot find a solution to my problem. I have a JSON which I need to add a list.

For example:

{
  "orders": "food"
}

I need to inject this list of items below the orders attribute.

{
  "items": [
  {
   "item": "ORD-X11",
   "buyer": "BY-001-001",
   "date": "060220"
  }
 ]
}

So the expected result is:

{
  "orders": "food"
  "items": [
  {
   "item": "ORD-X11",
   "buyer": "BY-001-001",
   "date": "060220"
  }
 ]
}

This is my code in JSON Patch:

{"op": "add", "path": "/items",
                      "value": {}
                      }
{"op": "add", "path": "/items/0",
                      "value": {"item": "ORD-X11"}
                      }
{"op": "add", "path": "/items/0",
                      "value": {"buyer": "BY-001-001"}
                      }
{"op": "add", "path": "/items/0",
                      "value": {"date": "060220"}
                      }

Error is appearing that the doc path is missing "/items" which I am trying to add.

wp78de
  • 18,207
  • 7
  • 43
  • 71
Yejin
  • 541
  • 2
  • 15
  • 32

1 Answers1

1

I've also only recently run into JSON-Patch and found this question interesting; after reading the fast-json-patch docs and with some trial and error I came up with this solution to your problem:

.as-console-wrapper { max-height: 100% !important; top: 0; }
<script type="module">
  import * as jsonpatch from 'https://cdn.jsdelivr.net/npm/fast-json-patch@3.0.0-1/index.mjs';
  import { applyOperation } from 'https://cdn.jsdelivr.net/npm/fast-json-patch@3.0.0-1/index.mjs';
  
  var document = {"orders": "food"};
  var patch = [
      {"op": "add", "path": "/items",
          "value": [{"item": "ORD-X11","buyer": "BY-001-001","date": "060220"}]
      }
  ];
  document = jsonpatch.applyPatch(document, patch).newDocument;
  console.log(document);
</script>

As you can see, we can patch the entire sub-object at once. Lovely.

wp78de
  • 18,207
  • 7
  • 43
  • 71