How to have different sets for different condition if I have declared a default set in @derive Jason.Encoder

Hi community,

I am facing a situation where I have to return a different encoded result, but I already have this set declared in my struct:


defmodule MyApp.Context.Example do
  use Ecto.Schema
  import Ecto.Changeset
  # ... aliases ...

  @derive {
    Jason.Encoder,
    only: [
      :id,
      :title,
      :type,
      :comments
  }

I am trying to preload and return only [:id, :title]. Is there any way I could redefine the @drive or any better solution for this circumstance?

Thank you all so much in advance! :heart:

Hi @enkr1 this is why it’s generally not recommended to derive Jason.Encoder for your structs, and instead use dedicated functions to extract the data you need. If it’s for an API, this article is still relevant: JSON Views in Phoenix | RokkinCat

2 Likes

Hi @benwilson512, thank you for your time to find the relevant article!

I see! This was actually my old solution, but I found myself repeating Map.take/2 and so I refactored to use Jason.Encoder which saved me quite some time, only until this edge case (to display specific attributes only) happens.

But yes, this will be my solution for now!