nikokozak

nikokozak

Re-casting json-encoded structs gracefully

Hi all - I might have dug my own grave by going down this path, but now I’m just curious… What is the best way to re-cast data after decoding a struct that has been encoded as json in order to be persisted? I’m working with embedded_schemas nested in a map that gets encoded when persisted via Ecto/PSQL. A very simplified version looks like this:

defmodule App.InnerSchema do

  embedded_schema do
    field :a_field, :string
    field :date_scheduled, :utc_datetime
  end

end

defmodule App.ParentSchema do

  schema "parents" do

    # a series of App.InnerSchema-like structs, all slightly different,
    # get stored here like so:
    # %{ plugin_1: %InnerSchema{}, plugin_2: %ADifferentInnerSchema{}, etc.. }
    field :stored_here, :map

  end

end

I thought about defining an Ecto.Type for :embedded_here, but the problem I have is that per the nature of the program, I can never be entirely sure what embedded_structs have been included in the encoded map, and while I could check fields against a list of probable structs when loading, it doesn’t seem graceful. I also tried forcing Jason.Encoder to encode the __struct__ field from the original InnerSchema in order to rescue it when decoding: the idea being, I could then cast the values I extract from the decoded json map using Ecto.Changeset.cast(the_decoded_json, apply(S.to_e_A(the_decoded_struct_field), :__struct__, []), ~w(the_fields), _opts), as per this old thread but cast keeps giving me an error saying it expects a :map instead of the %InnerSchema{}.

This might be a bit convoluted all in all, but ultimately all I want is a way to easily cast/decode each field’s type (namely for more complex stuff, like datetimes and custom Types), according to the struct that field is nested in after Jason encoding. Now that I’m typing it out, I realize it’s also about rescuing as much as possible from the json encoding (i know, i know). Any nice ways to do this?

Marked As Solved

dimitarvp

dimitarvp

Making your own Ecto.Types and just recursively cast – which happens automatically when you declare your schemata well – I found is the best way, both in professional and hobby projects.

What’s troubling you? Yeah it’s a bit manual… the first time. You gain stronger data consistency guarantees though.

Also, where does the data come from? Should there be a tolerance for malformed inputs?

Also Liked

nikokozak

nikokozak

Yep - I’ve always avoided playing with the internals of data in other languages. I’m loving that I can do that with Elixir (responsibly).

Great, makes sense the Jason behaviour would be specified like that.

Again, thank you for your help @dimitarvp

Where Next?

Popular in Questions Top

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
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
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
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement