Output JSON response

Hi All,

Currently I have the list of companies in this format

companies= [
{“Please type employer name”, “”},
{“Google”, 2},
{“Accenture”, 3},
{“Microsoft”, 1},
{“Apple”, 4}
]

I want to output this in a JSON response.
I am trying with render function. But it is considering only the first tuple and throwing error.

(exit) an exception was raised:
** (Protocol.UndefinedError) protocol Jason.Encoder not implemented for {“Please type employer name”, “”}, of type Tuple, Jason.Encoder protocol must always be explicitly implemented. This protocol is implemented for the following type(s): MyFutureNow.TransferableBenefits, MyFutureNow.UntransferableBenefits, Ecto.Association.NotLoaded, Ecto.Schema.Metadata, Any, Atom, BitString, Date, DateTime, Decimal, Float, Integer, Jason.Fragment, List, Map, NaiveDateTime, Time

When I give normal string or simple map, it works fine. But how to give a list of tuples to render function to output as JSON response.

Please help.

TIA…

Hello,

JSON format has fewer types than Elixir language. It is not clear how to encode tuples and how to get tuples from JSON, so this task was put on developer’s shoulders.
You have to convert tuple to other JSON-compatible data type. The easiest way of doing this is to convert tuple to list right before encoding to JSON:

companies |> Enum.map(&Tuple.to_list/1) |> Jason.encode!()

Another way is to define an implementation of Jason.Encoder protocol for Tuple globally (read more here), but personally I don’t recommend this.

3 Likes

How do you want tuples encoded in your JSON?