Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Nested JSON parsing to structs

Tags:

json

elixir

Disclaimer: I've checked the question here and it does not answer mine.

I am trying to come up with a way for nested struct parsing of JSONs. Example:

{"name": "blah blah", "address": {"street": "smthing"}}

I want to reach this result:

%User{name: "blah blah", address: %Address{street: "smthing"}}

Because then it would be easier to plug validation (using Vex for exapmle).

I know that Poison supports the "as struct" option but it does not provide nesting. The above would be parsed:

%User{name: "blah blah", address: %{"street" => "smthing"}}. 

I know I could write a decoder implementation for module User but I guess that is not the intended use case and it would not be generic.

When wondering about an implementation I could not find a way to tell if an atom is a module... maybe I have to go with :code.is_loaded(module_name)?

Anyway, before trying an implementation I would like to know if there is something I am not seeing.

like image 500
Olinasc Avatar asked Jun 15 '15 21:06

Olinasc


1 Answers

I believe the above is now possible with Poison:

defmodule User do
  @derive [Poison.Encoder]
  defstruct [:address]
end

defmodule Address do
  @derive [Poison.Encoder]
  defstruct [:street]
end

Poison.decode(response, as: %User{address: %Address{}})
like image 96
Maikon Avatar answered Oct 22 '22 01:10

Maikon