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: %{}.

Last Post!

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

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
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
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40082 209
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
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement