Ecto jsonb postgres issue

I want to store jsonb both array and map. structure is very dynamic and its coming from Government sites and if we update front-end its a lot of work to convert/adjust to maps only. Is there a way/workaround that I can use, store and retrieve both json/map and array types which are valid for jsonb postgres type. I have tried to use source and copy to array type sourced field before calling cast pipeline if I get array in params(condition: Map.has_key?(params, "value") && is_list(value)). I am successfully able to save data but when retrieving from db I am getting cast error

field(:value, :map)
field(:value_array, {:array, :integer}, source: :value)

Note: Ecto version > 3 and postgres 10

Can you provide some sample data ?

:wave:

You can probably create a custom ecto type which would accept and load both arrays and maps.

defmodule IsItMapIsItArrayWhoKnowsEctoDoes do
  @behaviour Ecto.Type

  # ... other callbacks ...

  @impl true
  def load(value) when is_list(value) or is_map(value) do
    {:ok, value}
  end
end

I haven’t tried it though.

3 Likes

Sample Data
[234] or it can be %{value: "some value"}

Thanks, it worked just like magic