Custom jason encoder

In the docs its mentioned that we can implement the custom data types with jason instead of for: Any. But what if i wanted to write it for some custom attribute like for: [Ecto.Association.NotLoaded] .how can I make it work. This is the code

      defimpl Jason.Encoder, for: [Ecto.Association.NotLoaded] do
       def encode(%{__struct__: _} = struct, _options) do
        struct
        |> Map.from_struct()
        |> sanitize()
        |> Jason.encode!()
       end

     defp sanitize(map) do
    map
   |> Map.delete(:__meta__)
   |> Map.delete(:__struct__)
   |> Enum.map(fn
    {k, %Ecto.Association.NotLoaded{}} -> {k, "Not Loaded"}
    other -> other
  end)
  |> Enum.into(%{})
end
end

Its working fine for: Any. But throws an error if I change it Ecto.Association.NotLoaded.

       This protocol is implemented for: Any, Atom, BitString, Date, DateTime, Decimal, 
         Ecto.Association.NotLoaded

It means it implemented for Ecto.Association.NotLoaded. But how can i include it in the modules to see if it works or not. Or Do I have tell my module to use this encoder?

Thanks

:wave:

Try replacing

defimpl Jason.Encoder, for: [Ecto.Association.NotLoaded] do

with

defimpl Jason.Encoder, for: Ecto.Association.NotLoaded do

and

Jason.encode!()

with

Jason.Encode.map()

same error. Works fine for: Any. But throws error for this

Can you please show a full error and the input you wanted to encode? My assumption is, that you are trying to encode a changeset, and not the actual struct.

it seems like I have to add @derive to few more models to make the code work.
But how do i check if my custom encoder is working?