Ordering keys when encoding a json card using Poison

For reading, I would like to have a specific key order in the json file.

I know that the card key does not have any order, and then we should not rely on it, but since Poison cannot encode protectors, I don’t see how to do it.

iex(1)> %{from: "EUR", to: "USD", rate: 0.845} |> Poison.encode! "{\"to\":\"USD\",\"rate\":0.845,\"from\":\"EUR\"}" 

As a result, I would like to:

 "{\"from\":\"EUR\", \"to\":\"USD\", \"rate\":0.845}" 

What structure should I use to achieve this with Poison?

+6
source share
1 answer

Do you really want to do this? Probably the least bad way to do this would be to define a structure for your card, and then implement the Poison protocol for that structure.

It might look something like this:

 defmodule Currency do defstruct from: "", to: "", rate: 0 end 

then somewhere in your project implements a protocol

 defimpl Poison.Encoder, for: Currency do def encode(%Currency{from: from, to: to, rate: rate}, _options) do """ {"from": #{from}, "to": #{to}, "rate": #{rate}} """ end end 

and then

 Poison.encode!(%Currency{from: "USD", to: "EUR", rate: .845}) 

All that has been said, I really recommend not to do this. Ordered cards are always a terrible idea and lead to some really fragile and confusing behavior.

Consider using what's really ordered, like a list of lists

+1
source

All Articles