JSONPatch
CanIO uses a format loosely based on JSONPatch to express a sequence of operations to apply to a target JSON document. It is used to sync data between shared spaces.
Each JSONPatch operation expresses the addition, removal or replacement of data at a certain path in the JSON document.
Structure of a JSONPatch Operation
The basic structure of a JSONPatch operation is as follows:
{
"mimetype": "application/json",
"name": "object_name",
"op": "add/replace/remove",
"path": "/xxxx/xxxx/xxx",
"data": "{\"key\":\"value\"}"
}
mimetype | The mimetype of the data that being set at the path. |
name | The name of the json document which the operation should be applied to. When used with shared spaces, this indicates the name of the shared space. |
op | The operation that is being described. An "add" operation adds new data at a path, a "replace" operation replaces the data at a path, and a "remove" operation removes the data at a path. |
path | The path to the element that is the operation is being applied to. Read "Parsing the path element" below to understand how to use paths. |
data | The actual data that is being applied to the path. For "remove" operations, this should be empty. |
Using the "path" element
The path element describes a path within the JSON document. Since a JSON document is constructed of both hashes and arrays, each element within the path can refer to both data structures. When the element refers to a hash, it will be used to describe the relevant hash key. When the element refers to an array, it will be used to describe the id of the relevant item within the array. To support this, objects within arrays should always contain a unique "id" field.
For example, if we look at the following JSON document:
{
"contacts": [
{
"id": "1",
"name": "John Smith",
"email": "jsmith@gmail.com"
}
]
}
- To initially create this document, we would use an add operation with a root path of / with data containing the entire document (or an add operation with a path of contacts with data containing the contacts array)
- To add another contact with an id of 2, we would use an add operation with a path of /contacts/2 with data containing the new contact hash.
- To change the name of the contact with an id of 1, we would use a replace opreation with a path of /contacts/2/name with data containing the new name.
- To add a phone field to the contact with an id of 1, we would use add operation with a apth of /contacts/2/phone with data containing the phone number.
- To delete a contact with id of 2, we would use a remove operation with a path of /contacts/2 with an empty data.