Re:Changelog for Elixir v1.11
by grantjpowell on Saturday September 12, 2020 @02:27PM
(#24454353)
> 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
Hard to say without knowing more about your usecase but normally I reach for lenses [1]
Re:Changelog for Elixir v1.11
by freedomben on Saturday September 12, 2020 @02:19PM
(#24454297)
Thanks, I haven't heard of lens before.
For others there's a blog post that introduces it: https://yapee.svbtle.com/nested-data-structures-with-lens
Part of what I suspect might make it feel less general purpose is that unless you spend time really learning the internals then it seems somewhat mysterious and constraining. The immutability for example (which most of the time I love) made it a nightmare when I was trying to process and transform deeply nested JSON. I tried a few times in Elixir and just bailed to Ruby where I could directly mutate stuff 5 levels down with ease and efficiency. The code seemed way more straight forward and readable.
How do people deal with things like deeply nested JSON in Elixir? Is there a way to make use of actors to avoid some of the pain points?