Telepath (Telepath v0.1.3) View Source
Provide an easy way to access elixir's data struct with a path.
Inspired by JsonPath & xPath (for json and xml), Telepath allows you to reach the data that you want, simply by specifying a path.
The path can be created using the sigil: ~t (see
Telepath.sigil_t/2
).
Link to this section Summary
Functions
Obtains a data at a given path.
Transform the struct path to an array that defines how to access the data.
Link to this section Types
Specs
Link to this section Functions
Obtains a data at a given path.
Telepath.get(%{hello: "world"}, ~t/hello/a)
# "world"
Telepath.get(%{foo: [%{bar: "bar1"}, %{bar: "bar2"}]}, ~t/foo.bar/a)
# ["bar1", "bar2"]
# works also with string key
Telepath.get(%{"foo" => [%{"bar" => "bar1"}, %{"bar" => "bar2"}]}, ~t/foo.bar/)
# ["bar1", "bar2"]
Telepath.get(%{foo: [%{bar: "bar1"}, %{bar: "bar2"}]}, ~t/foo/a)
# [%{bar: "bar1"}, %{bar: "bar2"}]
Telepath.get(%{foo: [%{bar: "bar1"}, %{bar: "bar2"}]}, ~t/*/a)
# [%{bar: "bar1"}, %{bar: "bar2"}]
If you want to map every case in the path, you can use :*
.
e.g.
Telepath.get(
%{data: %{key1: "value1", key2: "value2"}},
~t/data.*/a
)
# ["value1", "value2"]
See
sigil_t/2
for more informations on path.
opts
flatten
Return a flattened list (works only if the result of telepath is a list) (defaultfalse
).
Specs
Transform the struct path to an array that defines how to access the data.
Use
~t
instead of&Telepath.sigil_t/2
.
Modifiers
The modifiers available when creating a Telepath are:
- atom (a) - enable atom keys for path exploration.
Special characters
*
: will be transformed to:*
(see*
inTelepath.get/3
)
Examples
iex> Telepath.sigil_t("node")
["node"]
iex> Telepath.sigil_t("node.attr1")
["node", "attr1"]
iex> Telepath.sigil_t("node[0]")
["node", 0]
iex> Telepath.sigil_t("node[0].attr1")
["node", 0, "attr1"]
iex> Telepath.sigil_t("node.0.attr1")
["node", "0", "attr1"]
iex> Telepath.sigil_t("node.*.attr1")
["node", :*, "attr1"]
With the sigil ~t
it will be as simple as:
~t/data/
# ["data"]
~t/data/a
# [:data]