I want to load a json (list of objects) into list of structs in a module attribute.
Seems like I need three modules for that.
json
[
{"foo": 1, "bar": 2},
{"foo": 11, "bar": 22}
]
struct
defmodule Foo do
defstruct [:foo, :bar]
end
load into struct, note that function in reality is too complex to be added to Foos/@foos - pipe
defmodule JsonLoader do
def load_foos(foos) do
Enum.map(foos, &struct(Foo, &1))
end
end
module that stores the structs in a module attribute.
defmodule Foos do
@foos File.read!("lib/foos.json") |> Jason.decode!(keys: :atoms) |> JsonLoader.load_foos()
def get_foo(foo) do
Enum.find(@foos, fn f -> f.foo == foo end)
end
end
Is there way to bring all that into one module (Foo).






















