fireproofsocks

fireproofsocks

Convert Map to JSON when saving to database?

I’ve got an Ecto schema that has a column where I store some random data from a 3rd-party provider. This is mostly just for book-keeping purposes so we can search/parse it later if needed. In the database, this meta column is defined as a string. In my code, I end up with a Map which represents the data that I wish to store.

My question is: what’s the most elegant way to convert the Map to JSON on the way into the database and convert it back into a map on the way out? Could this accomplished via a custom Ecto.Type (I think yes)? Or should it be handled via some other means?

Thanks for recommendations/thoughts!

Marked As Solved

axelson

axelson

Scenic Core Team

If you’re using postgres I’d recommend storing the field as jsonb in the database instead of a string, then if you have a field :metadata, :map ecto will handle the serialization for you (and you can even query and index directly on fields inside the jsonb column)

Also Liked

fireproofsocks

fireproofsocks

Just to be thorough for future visitors, here’s the full example:

From my migration:

# ...
# (The :map type gets mapped to :jsonb for PostGres from what I understand)
add :meta, :map, default: "{}"  # <-- assuming I always want to store a JSON object

From my schema:

# ...
field :meta, :map, null: false, default: "{}"

And how it all works:

attrs = %{
    # ...
    meta: %{
        arbitrary: "stuff"
    }
}
result = %MyThing{}
  |> MyThing.changeset(attrs)
  |> Repo.insert()

  # result:
  %Auth.Schemas.AuthorityUser{
      __meta__: #Ecto.Schema.Metadata<:loaded,"my_thing">,
      # ...
      meta: %{
          "arbitrary" => "stuff",
      },
     # ...
  }
dimitarvp

dimitarvp

I believe that in your migration file(s) and schema module(s) you can replace the "{}" string literal with a map literal: %{}.

Where Next?

Popular in Questions Top

jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
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
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement