14

我试图找出修补对象集合的最佳方法。我正在尝试更改许多对象的排序顺序,并且认为 jsonpatch 可能是正确的方法。我的对象看起来像:

[
  {
    "ID": "100",
    "FirstName": "John",
    "LastName": "Smith",
    "Email": "jsmith@test.com",
    "SortOrder": 1
  },
  {

    "ID": "125",
    "FirstName": "John",
    "LastName": "Doe",
    "Email": "jdoe@test.com",
    "SortOrder": 3
  },
  {

    "ID": "50",
    "FirstName": "james",
    "LastName": "johnson",
    "Email": "jjohnson@test.com",
    "SortOrder": 2
  },
]

我创建了一个端点,它允许补丁请求使用 jsonpatch 请求更新集合中的多个对象,如下所示:

[
  {
    "op": "replace",
    "path": "/1/SortOrder",
    "value": 2
  },
  {
    "op": "replace",
    "path": "/0/SortOrder",
    "value": 1
  },
  {
    "op": "replace",
    "path": "/2/SortOrder",
    "value": 3
  }
]

我想要做的是在 jsonpatch 路径中使用 ID 属性。我当前的对象结构可能吗?它看起来像:

[
  {
    "op": "replace",
    "path": "/125/SortOrder",
    "value": 2
  },
  {
    "op": "replace",
    "path": "/100/SortOrder",
    "value": 1
  },
  {
    "op": "replace",
    "path": "/50/SortOrder",
    "value": 3
  }
]

我需要做什么才能发出这样的补丁请求?

4

2 回答 2

20

基于Json 指针 RFC,无法通过某些属性从数组中选择元素。由于JSON Patch使用 JSON Pointer,因此您很不走运。

JSON Patch 的人没有选择JSON Path或类似的东西作为选择语言,这太糟糕了。

于 2017-04-07T23:55:29.683 回答
-2

试试这个功能:

export function generateJsonPatch(obj: Object, patchObject = [], parent: string = null): Object[] {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key] instanceof Object) {
        if (parent) {
          parent = parent + '/' + key;
        } else {
          parent = key;
        }
        generateJsonPatch(obj[key], patchObject, parent);
      } else if (obj[key]) {
        let fieldName;
        if (parent) {
          fieldName = parent + '/' + key;
        } else {
          fieldName = key;
        }
        const patchField = { op: 'replace', path: `/${fieldName}`, value: `${obj[key]}` };
        patchObject.push(patchField);
      }
    }
  }
  return patchObject;
}

// USAGE:
const test = {
  'a': '1',
  'b': '2',
  'c': [{
    'd': '4',
    'e': '5'
  }]
};

generateJsonPatch(test);
// it will generate
// [{ "op": "replace", "path": "/a", "value": "1" },
//  { "op": "replace", "path": "/b", "value": "2" },
//  { "op": "replace", "path": "/c/0/d", "value": "4" },
//  { "op": "replace", "path": "/c/1/e", "value": "5" }]

于 2018-08-19T11:11:08.313 回答