|
|
|
|
|
by grantjpowell
2109 days ago
|
|
> How do people deal with things like deeply nested JSON in Elixir? Have you gotten to play with the `put_in/2` [0] and `update_in/2` [1] macros? They're designed to manipulate deeply nested structures like JSON iex(2)> my_parsed_json = %{"some" => %{"deeply" => %{"nested" => %{"key" => 1}}}}
%{"some" => %{"deeply" => %{"nested" => %{"key" => 1}}}}
iex(3)> update_in(my_parsed_json["some"]["deeply"]["nested"]["key"], & &1 + 1)
%{"some" => %{"deeply" => %{"nested" => %{"key" => 2}}}}
As a side note, a common misconception is that updating a large data structure on the BEAM is inefficient because values are immutable, so you have to copy the whole structure to make a tiny change. This is untrue, as Elixir (and Erlang) "maps" are implemented as HAMTs[2], which support very memory efficient updates by "sharing" the unchanged parts between the the old and updated maps.[0] https://hexdocs.pm/elixir/master/Kernel.html#put_in/2 [1] https://hexdocs.pm/elixir/master/Kernel.html#update_in/2 [2] https://en.wikipedia.org/wiki/Hash_array_mapped_trie |
|