michalmuskala / jason

A blazing fast JSON parser and generator in pure Elixir.
Other
1.61k stars 169 forks source link

Jason opts argument .encode clarification #149

Closed morgz closed 2 years ago

morgz commented 2 years ago

I'm trying to have a few different encoders for a particular module. I was hoping to pass a keyword argument in the opts argument when I call Jason.encode/2

However the opts look like this: {#Function<3.101187454/3 in Jason.Encode."-fun.escape_json/3-">, #Function<1.101187454/3 in Jason.Encode."-fun.map_naive/3-">}

My attempt: payload = Jason.encode(response, [option: "example"])

I was then hoping to handle this in:

defimpl Jason.Encoder, for: __MODULE__ do
  def encode(value, opts) do
  end
end
michalmuskala commented 2 years ago

Those options should be treated as mostly opaque and are only there to be passed as arguments to various helper functions in Jason.Encode module. Passing custom data in there is not supported.

I'd suggest passing this information inside of the data structure to encode.

Docs improvements are definitely welcome!

morgz commented 2 years ago

Thanks Michael. In this example if I passed{:full_json, %__MODULE__{... my actual struct}} to the first argument, 'value' of encode/2 would it find my implementation of the encoder? I'd assumed, possibly wrongly that it matched the module of my value to the defimpl Jason.Encoder, for: __MODULE__ do declaration.

so would it need to be defimpl Jason.Encoder, for: {:full_json, __MODULE__} do?

michalmuskala commented 2 years ago

I'm sorry, I'm not sure I understand your question.

In general this builds on the Elixir's protocol idea - normally you can only dispatch on the data types, in particular on structs.

michalmuskala commented 2 years ago

Closing for lack of follow-up