quazar

quazar

How to encode ecto schema with Jason with all fields

How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes. Just want it simple without much config.

@derive {Jason.Encoder, except: [:__meta__, :__struct__]} 

I tried this but it failed when association was not loaded. Is there a way I can specify to encode all attributes of schema and association which are preloaded and drop associations which are not loaded.

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

You’ve tagged this with Phoenix which makes me think you’re doing this in order to render a schema for an API. The suggested approach is to not do this with encoder protocols but rather with JSON views: https://www.rokkincat.com/blog/2015/03/17/json-views-in-phoenix

scooter

scooter

If anyone stumbles across this, the blog post referenced regarding why to use JSON views versus encoder protocols has changed URLs: https://rokkincat.com/blog/2015-03-17-json-views-in-phoenix/

amnu3387

amnu3387

You can define the Jason.Encoder protocol for the structure you want, so that it automatically does that, although I’m not positive this should be done instead of explicitly loading or discarding the fields according to where in the code you’re accessing the records, since this will discard that information always, e.g:

defimpl Jason.Encoder, for: [Your.Module] do
  def encode(struct, opts) do
    Enum.reduce(Map.from_struct(struct), %{}, fn
      ({k, %Ecto.Association.NotLoaded{}}, acc) -> acc
      ({k, v}, acc) -> Map.put(acc, k, v)
    end)
    |> Jason.Encode.map(opts)
  end
end

Notice now that this becomes implicit behaviour whenever Jason’s encode is called on this structure.

Other ways of doing it is to have a function that you call at the end of your load, or explicitly querying with a select, substituting the values explicitly when you don’t need them (this makes it so, that it’s explicit on the code actually running where that step is happening, instead of a catch all) e.g:

YourSchema |> where([ys], ys.id == 1) |> select([ys], %YourSchema{ys | associaton_field: nil}) |> Repo.one
amnu3387

amnu3387

I imagine the reply is meant to @quazar - I said “probably” you shouldn’t use the encoder, but nonetheless using the protocol is the only way to really set “Jason to encode all fields in ecto schema”. I do agree that if it’s in phoenix and you’re using views then it makes sense to use that instead. If not using phoenix, or not wanting to define a jason view, then it’s still better to make it explicit instead of relying on the protocol.

julismz

julismz

Some years later, I solved this just creating a module called jason_encoder.ex on lib/MyApp root folder:

defimpl Jason.Encoder, for: Any do
  def encode(%{__struct__: _} = struct, opts) do
    struct
    |> Map.from_struct()
    |> sanitize_map()
    |> Jason.Encode.map(opts)
  end

  defp sanitize_map(map) do
    map
    |> Map.drop([:__meta__, :__struct__])
    |> Enum.reduce(%{}, fn {key, value}, acc ->
      value =
        case value do
          %Ecto.Association.NotLoaded{} -> nil
          _ -> value
        end

      Map.put(acc, key, value)
    end)
  end
end

And that’s all… No need to do anymore.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
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
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
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

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
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
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New

We're in Beta

About us Mission Statement