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

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49266 226
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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

We're in Beta

About us Mission Statement