A Swift 5 implementation for IETF JSON-patch (RFC 6902).
iOS 8+
macOS 10.9+
SwiftyJSONPatch defines JSONPatcher value type.JSONPatcher applies JSON-patches to JSON documents.
import SwiftyJSONPatch
letjson=""" { "foo": 1, "bar": "baz", "baz": null }""".data(using:.utf8)!
letpatch=""" [ { "op": "test", "value": "baz", "path": "/bar" }, { "op": "remove", "path": "/baz" }, { "op": "add", "path": "/toto", "value": [1, 2, 3] }, { "op": "replace", "path": "/toto/2", "value": "baz" }, { "op": "copy", "from": "/foo", "path": "/toto/0" }, { "op": "move", "from": "/bar", "path": "/foo" }, ]""".data(using:.utf8)!
letpatcher=JSONPatcher()do{letpatched=try patcher.apply(patch, on: json)iflet result =String(data: patched, encoding:.utf8){print(result) // {"foo":"baz","toto":[1,1,2,"baz"]}
}}catch{print("Error: \(error)")}The JSONPatcher.PatchingError enum represents error cases JSONPatcher may throw while applying a patch :
publicenumPatchingError:Error{case document(Error) // failed to decode document JSON data
case patch(Error) // failed to decode patch JSON data
case operation(String,OperationError) // failed to apply specific patch operation
}The associated values gives you details about what have gone wrong.
The JSONPatcher.OperationError describes error cases while trying to perform patch operations :
publicenumOperationError:Error{case indexOutOfBounds(Int) // index out of bounds (index)
case memberNotFound(String) // member not found (name)
case notACollection // neither an array, nor an object
case notAnObject // not an object
case testFailure // test operation failed
case illegalMove(String,String) // wrong paths in move operation (from, path)
}Add github "vincedev/SwiftyJSONPatch" to your Cartfile.
You'll need SwiftLint to build the framework from source.
Clone the repository, open SwiftyJSONPatch.xworkspace.
Build the target for your preferred platform.
Open an issue if you have found a bug, or have a feature request.