class Json::Tools::Patch

Overview

An implementatition of https://datatracker.ietf.org/doc/rfc6902

This class represent a JSON patch object that can be applied to another JSON object, simply pass the patch object upon construction and then apply on the target document:

json_patch = JSON.parse ...
json_obj = JSON.parse ...
patch = Json::Tools::Patch.new(json_patch)
patched_obj = patch.apply(json_obj)

Defined in:

json-tools/patch.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(patch : JSON::Any) #

[View source]

Instance Method Detail

def apply(document : JSON::Any) #

Applies this patch on the given JSON object.

json_patch = JSON.parse(<<-JSON
  [
    { "op": "add", "path": "/n", "value": [1, 2, 3] },
    { "op": "remove", "path": "/a" },
    { "op": "replace", "path": "/c/1", "value": "new" }
  ]
  JSON
)
json_obj = JSON.parse(<<-JSON
  {
    "a": "a val",
    "b": 123,
    "c": ["first", "old", "last"]
  }
  JSON
)
patch = Json::Tools::Patch.new(json_patch)
patched_obj = patch.apply(json_obj) # => { "b": 123, "c": ["first", "new", "last"], "n": [1, 2, 3] }

[View source]