From 704bcb9c10d9ca30cc1e95cf499146ff6eee3b6b Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Tue, 24 Nov 2026 20:52:53 +0530 Subject: [PATCH] Return an error for paths through scalars and missing list elements --- lib/jsonpatch/utils.ex | 11 +++++++++-- test/jsonpatch_test.exs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/lib/jsonpatch/utils.ex b/lib/jsonpatch/utils.ex index 15f270d..ca61f1c 100644 --- a/lib/jsonpatch/utils.ex +++ b/lib/jsonpatch/utils.ex @@ -300,12 +300,19 @@ defmodule Jsonpatch.Utils do end defp find_destination(target, path, [fragment | tail], opts) when is_list(target) do - with {:ok, index} <- cast_fragment(fragment, path, target, opts) do - val = Enum.fetch!(target, index) + with {:ok, index} <- cast_fragment(fragment, path, target, opts), + {:ok, val} <- fetch(target, index) do find_destination(val, path ++ [fragment], tail, opts) + else + {:error, :invalid_path} -> {:error, {:invalid_path, path ++ [fragment]}} + {:error, _} = error -> error end end + defp find_destination(_target, path, [fragment | _tail], _opts) do + {:error, {:invalid_path, path ++ [fragment]}} + end + defp do_update_destination(_target, value, _path, :root, _opts) do {:ok, value} end diff --git a/test/jsonpatch_test.exs b/test/jsonpatch_test.exs index b80aba8..f4d60e4 100644 --- a/test/jsonpatch_test.exs +++ b/test/jsonpatch_test.exs @@ -839,6 +839,36 @@ defmodule JsonpatchTest do Jsonpatch.apply_patch(patch, target) end + test "Return an error when the path goes through a scalar or a missing list element" do + target = %{"name" => "Bob", "age" => nil, "hobbies" => [%{"x" => 1}]} + + paths = [ + {"/name/first", ["name", "first"]}, + {"/age/years/min", ["age", "years"]}, + {"/hobbies/0/x/y", ["hobbies", "0", "x", "y"]}, + {"/hobbies/1/x", ["hobbies", "1"]}, + {"/hobbies/-/x", ["hobbies", "-"]} + ] + + for {path, fragments} <- paths, + patch <- [ + %{"op" => "add", "path" => path, "value" => 1}, + %{"op" => "test", "path" => path, "value" => 1}, + %{"op" => "copy", "from" => path, "path" => "/new"}, + %{"op" => "move", "from" => path, "path" => "/new"}, + %{"op" => "copy", "from" => "/name", "path" => path} + ] do + assert {:error, + %Jsonpatch.Error{ + patch: ^patch, + patch_index: 0, + reason: {:invalid_path, ^fragments} + }} = Jsonpatch.apply_patch(patch, target) + + assert {:ok, ^target} = Jsonpatch.apply_patch(patch, target, ignore_invalid_paths: true) + end + end + test "Apply patch with multiple operations with binary keys" do patch = [ %Jsonpatch.Operation.Remove{path: "/age"},