JSONPointer
Implementation of RFC 6901 which defines a string syntax for identifying a specific value within a JSON document.
Usage
Preleminary note: the actual parsing of the JSON document is outside of the scope of this library, feel free to select on the several libraries available.
The resolve/2
and resolve!/2
functions expect to receive documents in the form of nested maps and lists,
as produced by most JSON parsers.
iex> document = %{
...> "key" => "value",
...> "list" => [1, 2, 3],
...> "deeply" => %{"nested" => %{"values" => [%{"x" => 1}, %{"x" => 2}]}}
...> }
iex> JSONPointer.resolve(document, "/key")
{:ok, "value"}
iex> JSONPointer.resolve(document, "/list/1")
{:ok, 2}
iex> JSONPointer.resolve(document, "/deeply/nested/values/0")
{:ok, %{"x" => 1}}
iex> JSONPointer.resolve(document, "/deeply/nested/values/1/x")
{:ok, 2}
iex> JSONPointer.resolve(document, "/list/4")
{:error, "index 4 out of bounds in [1, 2, 3]"}
Summary↑
escape(string) | Escapes a string in order to be usable as reference token |
resolve!(document, expr) | Resolves a JSON Pointer |
resolve(document, arg2) | Resolves a JSON Pointer |
Types ↑
json_object :: %{}
json_value :: nil | true | false | list | float | integer | String.t | json_object
Functions
Specs:
Escapes a string in order to be usable as reference token.
iex> JSONPointer.escape("/esc~aped")
"~1esc~0aped"
Specs:
- resolve(json_object, String.t) :: {:ok, json_value} | {:error, String.t}
Resolves a JSON Pointer expr
against the given document
and
returns {:ok, value}
on success and {:error, message}
otherwise.
iex> JSONPointer.resolve(%{"key" => "value"}, "/key")
{:ok, "value"}
iex> JSONPointer.resolve(%{"key" => "value"}, "/bogus")
{:error, "reference token not found: \"bogus\""}
Specs:
- resolve!(json_object, String.t) :: json_value | no_return
Resolves a JSON Pointer expr
against the given document
and
returns the referenced value.
Raises an ArgumentError
exception if an error occurs
iex> JSONPointer.resolve!(%{"key" => "value"}, "/key")
"value"
iex> JSONPointer.resolve!(%{"key" => "value"}, "/bogus")
** (ArgumentError) reference token not found: "bogus"