Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to return encode :date types in Poison

I'm using the default json tools in Phoenix, but for some reason I can't return any dates (field type :date). I get something like this:

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

I'm using a postgres db with the field in the db of type date. Am I missing something? Do I need to build a function to parse the date before I encode it with poison?

like image 971
Dania_es Avatar asked Mar 26 '15 03:03

Dania_es


2 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 format your date into a string first, Posion will have no trouble encoding it into 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.

like image 155
Jordan Dimov Avatar answered Sep 18 '22 16:09

Jordan Dimov


This is going to get better in the next Phoenix release (v0.11):

  1. The new Phoenix version will automatically include encoders for Ecto.DateTime and Ecto.Date via the phoenix_ecto project. So it should just work™.

  2. That said, you likely want to use Ecto.DateTime, Ecto.Date and friends instead of :datetime and :time as you will work with structs and not tuples.

like image 43
José Valim Avatar answered Sep 20 '22 16:09

José Valim