Failed to return encoding: date types in Poison

I use the default json tools in Phoenix, but for some reason I cannot return dates (field type: date). I get something like this:

unable to encode value: {2015, 3, 24} 

I am using postgres db with a field in a db of type date. Am I missing something? Do I need to build a function for parsing a date before I encode it with poison?

+5
source share
3 answers

Your "date object" is just an elixir tuple. Posion does not know how to encode Elixir tuples:

 iex(1)> Poison.encode({2015, 3, 24}) {:error, {:invalid, {2015, 3, 24}}} 

If you first format the date into a string, Posion will have no problem encoding it in JSON:

 iex(2)> Poison.encode(:io_lib.format("~4..0B-~2..0B-~2..0B", [2015, 3, 24]) |> List.flatten |> to_string) {:ok, "\"2015-03-24\""} 

Hope this helps.

+4
source

Thanks to Jordan Dimov above, I ended up creating a module called formatter, which has a variant of this formatting and money formatting. Here it is, if this is useful to someone:

 defmodule Myapp.Formatter do def date(date) do :io_lib.format("~4..0B-~2..0B-~2..0B", Tuple.to_list(date)) |> List.flatten |> to_string end def money(money) do (money.coef/100)*money.sign end end 

I smoothed the module under: view in the myapp.Web module, so the functions are available in my views for formatting before returning Json. Thanks!

+1
source

This will improve in the next release of Phoenix (v0.11):

  • Encoders for Ecto.DateTime and Ecto.Date automatically included in the new version of Phoenix through the phoenix_ecto project. Therefore, it should just work ™.

  • However, you will most likely want to use Ecto.DateTime , Ecto.Date and friends instead of :datetime and :time , since you will be working with structures, not tuples.

+1
source

Source: https://habr.com/ru/post/1216151/


All Articles