★ YAML: JSON patch: test
• 312 words • 2 min
RFC 6902, JavaScript Object Notation (JSON) Patch:
JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JavaScript Object Notation (JSON) document; it is suitable for use with the HTTP PATCH method. The “application/json-patch+json” media type is used to identify such patch documents.
jsonpatch.me has a sandbox to play with it.
Example #
JSON:
{
"message": "Hello World",
"from": "Unknown"
}Patch (also a JSON!):
[
{ "op": "replace", "path": "/message", "value": "Patching JSON is fun" },
{ "op": "add", "path": "/with", "value": "jsonpatch.me" },
{ "op": "remove", "path": "/from" }
]Result:
{
"message": "Patching JSON is fun",
"with": "jsonpatch.me"
}YAML #
It’s also possible to use JSON Patch with YAML, because YAML is a superset of JSON:
YAML:
message: "Hello World"
from: "Unknown"The same JSON patch as before yields this result:
message: "Patching JSON is fun"
with: "jsonpatch.me"We could have expressed the patch in YAML form if we wanted to:
- op: replace
path: /message
value: Patching JSON is fun
- op: add
path: /with
value: jsonpatch.me
- op: remove
path: /fromTests? #
It’s intuitive to understand the basic JSON patch operations:
- add
- remove
- replace
- move
- copy
What comes off as surprising is that there’s also a test operation.
At this point I would recommend the reader to look at the spec, it’s quite readable.
Here is an example of how I typically use test:
- op: test
path: /spec/syncPolicy/syncOptions/3
value: ServerSideApply=true
- op: remove
path: /spec/syncPolicy/syncOptions/3Before removing an array element (which must be done by index), check that we’re removing the appropriate one.
Why? Because it is error-prone not to do so. If someone reorders the array for some reason, we would end up deleting the incorrect array element! Do you want to be the one writing up the postmortem?