我试图找出修补对象集合的最佳方法。我试图改变许多对象的排序顺序,并认为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
}
]
我需要做些什么才能提出这样的补丁请求?
答案 0 :(得分:8)
基于Json pointer RFC,无法通过某个属性从数组中选择元素。由于JSON Patch使用JSON指针,因此您运气不佳。
对于选择语言,JSON Patch人员没有选择JSON Path或类似的东西太糟糕了。
答案 1 :(得分:0)
尝试此功能:
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" }]