Documentation ¶
Overview ¶
Package diff computes diffs for updating JSON objects. It uses a lightweight field-by-field diffing algorithm suitable for comparing graphql result objects, but perhaps not for other JSON objects.
For each field, a diff represents an update as - a recursive diff, stored as an object. - a complex replacement of the original field's value, stored as the new value in a 1-element array. - a scalar replacement, stored as the raw new value. - a deletion of the old field, stored as a 0-element array.
For example, consider the following objects old, new, and the resulting diff:
old = { "name": "bob", "address": {"state": "ca", "city": "sf"}, "age": 30 } new = { "name": "alice", "address": {"state": "ca", "city": "oakland"}, "friends": ["bob", "charlie] } diff = { "name": "alice", "address": {"city": "oakland"}, "age": [], "friends": [["bob", "charlie]] }
The diff updates the name field to "alice", stored as a scalar. The diff updates the address recursively, keeping the state, but changing the city to "oakland". The diff deletes the age field with a 0-element array, and add a new complex friends field, stored in 1-element array.
Array diffs are represented as object diffs with an optional reordering field stored in the "$" property. This reordering field holds a compressed of indices, indicating for each value in the new array the location of the element in the previous array. This makes for small diffs of long arrays that contain some permuted objects.
For example, consider the following arrays old, new, and the resulting reordering:
old = [0, 1, 2, 3] new = [1, 2, 3, 4] reordering = [1, 2, 3, -1]
The reordering indicates that the first 3 elements of the new array can be found at positions 1, 2, 3 and of the old array. The fourth item in the new array was not found in the old array.
To compress this reodering array, we replace runs of adjacent indices as a tuple [start, length], so that the compressed reordering becomes
reordering = [1, 2, 3, -1] compressed = [[1, 3], -1]
Finally, to identify complex objects in arrays, package diffs uses a special "__key" field in objects. This must be a comparable value that allows the algorithm to line up values in arrays. For example,
old = [ {"__key": 10, "name": "bob", "age": 20"}, {"__key": 13, "name": "alice"} ] new = [ {"__key": 13, "name": "alice"} {"__key": 10, "name": "bob", "age": 23}, ] diff = { "$": [1, 0], "1": {"age": 23} }
Here, the diff first switches the order of the elements in the array, using the __key field to identify the two objects, and then updates the "age" field in the second element of the array to 23.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
This section is empty.