stefanchrobot
How to decode a JSON into a struct safely?
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with string keys, but struct() expects atom keys.
Most Liked
LostKobrakai
Map.new(%Foo{}, fn {key, _} -> {key, json[Atom.to_string(key)]} end)
joefractal
Quick example
defmodule Foo do
@derive [Poison.Encoder]
defstruct [:bar]
end
defmodule Example do
def test do
s = "{\"bar\":\"baz\"}"
Poison.decode!(s, as: %Foo{})
end
end
iex(1)> Example.test
%Foo{bar: “baz”}
There are probably more modern ways to do it, but this is was I have been using. You can also nest structs this way.
The number of json encode/decoders seems to grow everyday. https://package-rank.com/wp/hex/poison/-vs-/hex/jason
axelson
You can also always decode manually and completely explicitly. It is more typing but it also allows you to change the struct or the parameters independently. It is not always the best way but sometimes is.
defmodule Foo do
defstruct [:bar, :baz]
end
defmodule Example do
def test do
s = '{"bar":"abc", "baz": 42}'
json = Poison.decode!(s)
%Foo{
bar: json["bar"],
baz: json["baz"],
}
end
end
Gee-Bee
moogle19
Quick question: Why not use Ecto.Enum for the job and {:array, Ecto.Enum} for the hobbies?







