dpreston

dpreston

Decoding Json with nested lists of dissimilar structs

Is there a built-in way to decode json that has a list of objects that are not decoded to the same struct, and the list is not at the root of the json?
Its a large, deeply nested json payload from a 3rd party, and I would prefer not to recursively decode and replace each list, but thats the only solution I have so far. Any suggestions would be appreciated.

Poison can do this if the list is the root,

defmodule TypeA do
  defstruct shared: "", only_a: ""
end

defmodule TypeB do
  defstruct shared: "", only_b: ""
end

options = fn
  %{only_a: _a} -> %TypeA{}
  %{only_b: _b} -> %TypeB{}
end

"""
[
  {
    "shared": "value",
    "only_a": "A!"
  }, 
  {
    "shared": "value",
    "only_b": "B!"
  }
]
"""
|> Poison.decode!([keys: :atoms!, as: [options]])
[
  %TypeA{shared: "value", only_a: "A!"}, 
  %TypeB{shared: "value", only_b: "B!"}
]

but if there is a parent struct, the children objects just decode to plain maps.

defmodule Parent do
  defstruct children: []
end

"""
{ 
  "children": [
    {
      "shared": "value",
      "only_a": "A!"
    }, 
    {
      "shared": "value",
      "only_b": "B!"
    }
  ]
}
"""
|> Poison.decode!( as: %Parent{})
%Parent{
  children: [
    %{"only_a" => "A!", "shared" => "value"}, 
    %{"only_b" => "B!", "shared" => "value"}
  ]
}

I’ve tried adding the as: function to the %Parent{} struct definition, but its not a valid value.

defmodule Parent do
  children = fn
    %{only_a: _a} -> %TypeA{}
    %{only_b: _b} -> %TypeB{}
  end

  defstruct children: children # <- invalid value
end

Marked As Solved

dpreston

dpreston

Thanks @mudasobwa, for prompting me to dig further into the decoders

I’ve gone with custom Poison decoders for each of the relevant structs. It’s really simple to just add the possible structs to the children_types in the decode function and it catches them all on the first pass instead of needing to rewalk the object until all the structs have been matched.

defmodule TypeA do
  defstruct shared: "", only_a: ""
end

defmodule TypeB do
  defstruct shared: "", only_b: ""
end

defmodule Parent do
  defstruct name: "", children: []
end

defimpl Poison.Decoder, for: Parent do
  def decode(value, options) do
    children_types = fn
      %{only_a: _a} -> %TypeA{}
      %{only_b: _b} -> %TypeB{}
    end

    value
    |> Map.update!(:children, fn children ->
      children
      |> Enum.map(
        &Poison.Decode.transform(
          &1,
          Map.put(options, :as, children_types)
        )
      )
    end)
  end
end
"""
{ 
  "name": "parent",
  "children": [
    {
      "shared": "value",
      "only_a": "A"
    }, 
    {
      "shared": "value",
      "only_b": "B"
    }
  ]
}
"""
|> Poison.decode!(keys: :atoms!, as: %Parent{})
%Parent{
  name: "parent",
  children: [
    %TypeA{shared: "value", only_a: "A"}, 
    %TypeB{shared: "value", only_b: "B"}
  ]
}

Also Liked

mudasobwa

mudasobwa

Creator of Cure

Another option would be a custom Poison’s encoder implementation for structs like Parent.

I would nevertheless stick with straight parsing into maps and then upgrading them to structs with update_in/3 through Access. That’d be more explicit. Like

%{root: %{lvl1: [%{only_a: :a}, %{only_b: :b}]}}
|> update_in([:root, :lvl1, Access.all()], options)

%{
  root: %{
    lvl1: [%TypeA{shared: "", only_a: ""}, %TypeB{shared: "", only_b: ""}]
  }
}```

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
stefanchrobot
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 st...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement