Encode a tuple of strings with poison

2.4k views Asked by At

I'm trying to encode this tuple of strings with poison:

{"product existed but could not add categories to product",
 "Shop existed but could not add product to shop"}

Getting this error:

19:10:21.593 [error] #PID<0.339.0> running Api.Router terminated
Server: 192.168.20.3:4000 (http)
Request: POST /products
** (exit) an exception was raised:
    ** (Poison.EncodeError) unable to encode value: {"product existed but could not add categories to product", "Shop ex
isted but could not add product to shop"}
        (poison) lib/poison/encoder.ex:383: Poison.Encoder.Any.encode/2
        (poison) lib/poison/encoder.ex:227: anonymous fn/4 in Poison.Encoder.Map.encode/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map."-encode/3-lists^foldl/2-0-"/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map.encode/3
        (poison) lib/poison.ex:41: Poison.encode!/2
        (api) lib/api/router.ex:90: anonymous fn/1 in Api.Router.do_match/4
        (api) lib/api/router.ex:1: Api.Router.plug_builder_call/2
        (api) lib/plug/debugger.ex:123: Api.Router.call/2

Can Poison encode a tuple of strings or should I be changing my type for errors to be something else?

1

There are 1 answers

0
intentionally-left-nil On

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

defmodule TupleEncoder do
  alias Poison.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.