Ciboulette
Insert String, Integer, Map, List in a jsonb PostgreSQL column
Hi everybody,
I would like to know how can I insert data which can be a Map, String, List, Integer, Float in a jsonb PostgresSQL column ?
PostgreSQL is capable of doing such insertion in a jsonb field. I would like to find a way where Ecto (as an ORM) let me do this. Because currently my field is:
field(:data, :map) and it does not work when I try to insert: "toto" or 12 or [1,2]. And I have no other options, As I do not decide which type of data I’m receiving. Thanks ![]()
Marked As Solved
Eiji
@mischov: I think that this should work, but I did not fully tested it.
defmodule Type.Json do
alias Ecto.Type
@behaviour Ecto.Type
@moduledoc """
To store values that might be any json value.
Not intended as a general replacement for :map.
"""
def type, do: :json
def cast(value) when is_nil(value), do: {:ok, value}
def cast(value) when is_boolean(value), do: {:ok, value}
def cast(value) when is_binary(value), do: {:ok, value}
def cast(value) when is_number(value), do: {:ok, value}
def cast(value) when is_list(value), do: Type.cast({:array, __MODULE__}, value)
def cast(value) when is_map(value), do: Type.cast({:map, __MODULE__}, value)
def cast(_), do: :error
def load(data), do: {:ok, data}
def dump(value) when is_nil(value), do: {:ok, value}
def dump(value) when is_boolean(value), do: {:ok, value}
def dump(value) when is_binary(value), do: {:ok, value}
def dump(value) when is_number(value), do: {:ok, value}
def dump(value) when is_list(value), do: Type.dump({:array, __MODULE__}, value)
def dump(value) when is_map(value), do: Type.dump({:map, __MODULE__}, value)
def dump(_), do: :error
end
Also Liked
LostKobrakai
You can always create your own. The ecto type is a map type not a json one. In the end ecto is not bound to any db at all and it makes way more sense to have types, which align well to elixir than ones that align well with a certain database.








