(De)serializing JSON documents into Structs: Just include `__struct__`? Seemingly not quite

The UUID key in your output is an atom. If it was a string, the syntax would be "bfa..." => %{ instead of "bfa...": %{. As you suspected, this is risky.

Your __struct__ key has been included in the JSON as a string, and thus retrieved back as a string. But the value in an Elixir struct is an atom (the module name). So your struct is broken and Elixir shows it as a regular map. Jason doesn’t support decoding data into structs so you’ll need to do that yourself.

I’d decode with Jason without supplying keys: :atoms (because it’s dangerous) and then look for some library to validate/transform the data forward from that point. I think Ecto can also be used for this but I don’t have experience with that.

5 Likes