Sunday, 18 November 2018

JSON-Patch: Applying deltas to JSON Documents in Swift

I recently started looking at saving bandwidth between a client and server that communicates with JSON. Some of these messages send large JSON documents that do not change very frequently and when there are changes, they are small relative to the whole document. My search lead me to JSON-Patch  a IETF proposed standard (RFC 6902).  JSON-Patch is a patch format which itself is specified in JSON, it can perform operations on a target JSON document to transform it to the intended state. The standard has the following operations: -

  • add - Insert / Replace a value at the given location with a new value.
  • remove - Remove a value at the given location (value must exist).
  • replace - Replace a value at the given location with a new value (value must exist).
  • move - Move a value at the given location to a new location. Logically equivalent to a remove then add. (value must exist)
  • copy - Copies a value at the given location to a new location (value must exist).
I looked for implantations of JSON-Patch in Swift, and found one but it had dependences on SwiftlyJSON another swift module. Which is great if you're already using it in your project, but I wanted to work with the JSONSerialization that comes in Foundation directly. So I wrote my own JSONPatch swift module. This initial version can only apply patches, it does not currently generate patches based on two JSON documents. Project available here on GitHub.

Usage

JSONPatch can work with the Data representations of JSON.
However if you are already parsing the JSON with JSONSerialization within your project then JSONPatch can work with the parsed objects you already have. This can be especially useful if you want to apply a patch relative to sub-element of the whole JSON document.