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?
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.
This is going to get better in the next Phoenix release (v0.11):
The new Phoenix version will automatically include encoders for Ecto.DateTime
and Ecto.Date
via the phoenix_ecto project. So it should just work™.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With