Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Jason encode struct with tuple

Tags:

elixir

I have a struct which already has @derive Jason.Encoder but some fields in that struct are tuples, and for this reason cannot encode the struct, how can I fix that :/

UPDATE

I have used the approach that mentioned below with implementing a protocol. One important thing to note about this approach is that it will change the encoding for the whole project, just be careful with that !

like image 847
Tano Avatar asked May 16 '19 09:05

Tano


2 Answers

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.

like image 120
bxdoan Avatar answered Sep 28 '22 21:09

bxdoan


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

like image 21
mroach Avatar answered Sep 28 '22 21:09

mroach