View Source Jsonpatch

Elixir CI Coverage Status Generic badge Maintenance Hex.pm Version

An implementation of RFC 6902 in pure Elixir.

Features:

  • Creating a patch by comparing to maps and lists
  • Apply patches to maps and lists - supports operations:
    • add
    • replace
    • remove
    • copy
    • move
    • test
  • Escaping of "/" (by "~1") and "~" (by "~0")
  • Allow usage of - for appending things to list (Add and Copy operation)

getting-started

Getting started

installation

Installation

The package can be installed by adding jsonpatch to your list of dependencies in mix.exs:

def deps do
  [
    {:jsonpatch, "~> 1.0.1"}
  ]
end

The docs can be found at https://hexdocs.pm/jsonpatch.

create-a-diff

Create a diff

iex> source = %{"name" => "Bob", "married" => false, "hobbies" => ["Sport", "Elixir", "Football"]}
iex> destination = %{"name" => "Bob", "married" => true, "hobbies" => ["Elixir!"], "age" => 33}
iex> Jsonpatch.diff(source, destination)
{:ok, [
  %Jsonpatch.Operation.Add{path: "/age", value: 33},
  %Jsonpatch.Operation.Replace{path: "/hobbies/0", value: "Elixir!"},
  %Jsonpatch.Operation.Replace{path: "/married", value: true},
  %Jsonpatch.Operation.Remove{path: "/hobbies/1"},
  %Jsonpatch.Operation.Remove{path: "/hobbies/2"}
]}

apply-patches

Apply patches

iex> patch = [
  %Jsonpatch.Operation.Add{path: "/age", value: 33},
  %Jsonpatch.Operation.Replace{path: "/hobbies/0", value: "Elixir!"},
  %Jsonpatch.Operation.Replace{path: "/married", value: true},
  %Jsonpatch.Operation.Remove{path: "/hobbies/1"},
  %Jsonpatch.Operation.Remove{path: "/hobbies/2"}
]
iex> target = %{"name" => "Bob", "married" => false, "hobbies" => ["Sport", "Elixir", "Football"]}
iex> Jsonpatch.apply_patch(patch, target)
{:ok, %{"name" => "Bob", "married" => true, "hobbies" => ["Elixir!"], "age" => 33}}

important-sources

Important sources