0

我一直在阅读有关 JSON Patch 的信息。但是,我找不到解决问题的方法。我有一个 JSON,我需要添加一个列表。

例如:

{
  "orders": "food"
}

我需要在 orders 属性下注入这个项目列表。

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

所以预期的结果是:

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

这是我在 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"}
                      }

出现错误,文档路径缺少我要添加的“/items”。

4

1 回答 1

0

我也是最近才遇到 JSON-Patch 并发现这个问题很有趣;在阅读了fast-json-patch 文档并经过反复试验后,我想出了解决您问题的方法:

.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>

如您所见,我们可以一次修补整个子对象。迷人的。

于 2020-11-12T03:48:15.980 回答