unable to derive {Jason.Encoder} on defstruct _: ""

Hi,

I want to create a struct with two fields: _ and $ and should be able to json encode as {"_": "value", "$": "type"}. However, I can get over the error warning bellow

Is there any workaround?

I think that’s a bug in Jason.Encoder.Any. Try to define implementation for Entity struct explicitly.

Managed to get it works as per @fuelen suggestion

defmodule Entity do
  defstruct _: "", "$": ""
end

defimpl Jason.Encoder, for: Entity do
  def encode(%Entity{} = entity, _opts) do
    %{_: Map.get(entity, :_, ""), "$": Map.get(entity, :"$")} |> Jason.encode!()
  end
end

entity will always have keys defined in struct.
encoding can be simplified to

entity |> Map.take([:_, :"$"]) |> Jason.encode!()
2 Likes

But if the value is nil then èntity[:_] || "" should do what I assume was the desired behaviour.

1 Like