Json Merge Patch 描述了如何修改目标JSON 文档的一种格式,即如果被提供的merge patch 中存在目标文档中不存在的成员,则该成员将会新加;如果被提供的成员与目标成员都存在则做替换修改;在Merge Patch 中的null值意味着删除目标中该对象,
目标文档
{
"a": "b",
"c": {
"d": "e",
"f": "g"
}
}
merge patch 用于改变a的值,删除f,
PATCH /target HTTP/1.1
Host: example.org
Content-Type: application/merge-patch+json
{
"a":"z",
"c": {
"f": null
}
}
目标json文档
{
"title": "Goodbye!",
"author" : {
"givenName" : "John",
"familyName" : "Doe"
},
"tags":[ "example", "sample" ],
"content": "This will be unchanged"
}
merge patch
一个用户想要更改title的值,新加phoneNumber成员、content成员,删除givenName成员,修改tags的值,就可以发送以下请求
PATCH /my/resource HTTP/1.1
Host: example.org
Content-Type: application/merge-patch+json
{
"title": "Hello!",
"phoneNumber": "+01-123-456-7890",
"author": {
"familyName": null
},
"tags": [ "example" ]
}
最终结果
{
"title": "Hello!",
"author" : {
"givenName" : "John"
},
"tags": [ "example" ],
"content": "This will be unchanged",
"phoneNumber": "+01-123-456-7890"
}
Merge Patch Format 一般会使用HTTP协议中的PATCH方法进行发送请求,并且其 Content-Type类型为 application/merge-patch+json
JSON是数据结构化存储常用的数据格式,HTTP协议在原有的方法基础上,扩展出了PATCH方法,该方法使用JOSN PATCH格式的语法对数据进行加工。JSON PATCH格式的HTTP PATCH请求示例如下
PATCH /my/data HTTP/1.1
Host: example.org
Content-Length: 326
Content-Type: application/json-patch+json
If-Match: "abc123"
[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]
从上述可以看出该方式对应的Content-Type是application/json-patch+json;该语法格式中有三个重要的概念op、path、value;
其中op 必须是 “add”, “remove”, “replace”, “move”, “copy”, "test"中的其中一个,其他值是非法的。
{ "foo": "bar"}
JSON Patch document:
[
{ "op": "add", "path": "/baz", "value": "qux" }
]
结果 JSON document:
{
"baz": "qux",
"foo": "bar"
}
对于merge动作来说,一般情况下key值如果相同,则替换更改对应的值;如果key不存在则新增key成员,类似于JSON Merge Patch,但是在不同设计场景中又有所不同