diff --git a/lib/encoder.ex b/lib/encoder.ex index d693399..49f555b 100644 --- a/lib/encoder.ex +++ b/lib/encoder.ex @@ -77,7 +77,7 @@ end defimpl Jason.Encoder, for: Any do defmacro __deriving__(module, struct, opts) do fields = fields_to_encode(struct, opts) - kv = Enum.map(fields, &{&1, generated_var(&1, __MODULE__)}) + kv = Enum.map(fields, &{&1, generated_var(&1)}) escape = quote(do: escape) encode_map = quote(do: encode_map) encode_args = [escape, encode_map] @@ -94,9 +94,12 @@ defimpl Jason.Encoder, for: Any do end end - # The same as Macro.var/2 except it sets generated: true - defp generated_var(name, context) do - {name, [generated: true], context} + # The same as Macro.var/2 except it sets generated: true and handles _ key + defp generated_var(:_) do + {:__, [generated: true], __MODULE__.Underscore} + end + defp generated_var(name) do + {name, [generated: true], __MODULE__} end def encode(%_{} = struct, _opts) do diff --git a/test/encode_test.exs b/test/encode_test.exs index f4c0ef2..20d48b9 100644 --- a/test/encode_test.exs +++ b/test/encode_test.exs @@ -135,6 +135,11 @@ defmodule Jason.EncoderTest do defstruct name: "", size: 0 end + defmodule DerivedWeirdKey do + @derive Encoder + defstruct [:_] + end + defmodule NonDerived do defstruct name: "" end @@ -154,6 +159,9 @@ defmodule Jason.EncoderTest do derived_using_except = %DerivedUsingExcept{name: "derived using :except", size: 10} assert to_json(derived_using_except) == ~s({"size":10}) + + derived_weird_key = %DerivedWeirdKey{} + assert to_json(derived_weird_key) == ~s({"_":null}) end test "@derive validate `except:`" do