Home

Awesome

Jsonpatch

Elixir CI Coverage Status Generic badge Maintenance Hex.pm Version

An implementation of RFC 6902 in pure Elixir.

Features:

Getting started

Installation

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

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

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

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)
[
  %{path: "/married", value: true, op: "replace"},
  %{path: "/hobbies/2", op: "remove"},
  %{path: "/hobbies/1", op: "remove"},
  %{path: "/hobbies/0", value: "Elixir!", op: "replace"},
  %{path: "/age", value: 33, op: "add"}
]

Apply patches

iex> patch = [
  %{op: "add", path: "/age", value: 33},
  %{op: "replace", path: "/hobbies/0", value: "Elixir!"},
  %{op: "replace", path: "/married", value: true},
  %{op: "remove", path: "/hobbies/1"},
  %{op: "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