Elixir Jason encode struct with tuple

Have a look at the documentation for how you need to implement the encode/2 function: https://hexdocs.pm/jason/Jason.Encoder.html

As part of your implementation, you need to decide how you want to encode a tuple since it doesn't have an analog in JSON. An array is probably the easiest option, so you could do mytuple |> Tuple.to_list


If you do need to encode tuples as a list type, this works:

defmodule TupleEncoder do
  alias Jason.Encoder

  defimpl Encoder, for: Tuple do
    def encode(data, options) when is_tuple(data) do
      data
      |> Tuple.to_list()
      |> Encoder.List.encode(options)
    end
  end
end

You should be able to use a similar pattern to convert it to another primitive structure as needed.

Tags:

Elixir