问题
I have a question about the interpretation of JSON Patch (RFC 6902).
Suppose I had a resource that looked like this:
{
"type": "assembly",
"uri": "http://example.com/campSrv/Assembly/18",
"name": "/sample",
"description": "Hello, World Application",
"created": "2013-03-27T16:15Z",
...
}
The definition of this resource says that it could have a value called "tags" which is defined as being an array of strings. However, this resource currently has no tags, so my service doesn't serialize the non-existent array.
Now suppose I submit the following HTTP PATCH request:
PATCH http://example.com/campSrv/Assembly/18 HTTP/1.1
Content-Type: application/json-patch
[
{ "op": "add", "path": "/tags/0", "value": "flobbit" }
]
Should this create the 'tags' array and add 'flobbit' as the first/only element or should my server return an error?
回答1:
In my understanding ...
Your patch will result in an error because tags
does not exist, and you can't add to an array that does not yet exist.
RFC 6902 4.1
...
However, the object itself or an array containing it does need to
exist, and it remains an error for that not to be the case. For
example, an "add" with a target location of "/a/b" starting with this document:{ "a": { "foo": 1 } }
is not an error, because "a" exists, and "b" will be added to its
value. It is an error in this document:{ "q": { "bar": 2 } }
because "a" does not exist.
This patch, however, will add a tags
string with a value of "flobbit"
.
[
{ "op": "add", "path": "/tags", "value": "flobbit" }
]
And this patch will add tags
array with the first element being "fobbit"
.
[
{ "op": "add", "path": "/tags", "value": ["flobbit"] }
]
来源:https://stackoverflow.com/questions/15930516/interpretation-of-the-json-patch-spec