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 !
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With