Poison error on attempting to serialize a map

At a first attempt to serialize a map, I tried using Poision but I get an error … I assumed Poison could handle all data types … it doesn’t seem to like the tuple of tuples.
This shows the error … the {mtime: {{2019, 3, 16}, {23, 47, 17}}} was the entry in my larger map Poison didn’t like. When I take the :mtime item out of the map it works as expected.

Any help appreciated.

iex(1)> {:ok, %{mtime: mtime}} = File.stat("test.json")
{:ok,
 %File.Stat{
   access: :read_write,
   atime: {{2019, 3, 16}, {23, 47, 33}},
   ctime: {{2019, 3, 16}, {23, 47, 17}},
   gid: 1000,
   inode: 12189812,
   links: 1,
   major_device: 2053,
   minor_device: 0,
   mode: 33188,
   mtime: {{2019, 3, 16}, {23, 47, 17}},
   size: 245,
   type: :regular,
   uid: 1000
 }}
iex(2)> mtime
{{2019, 3, 16}, {23, 47, 17}}
iex(3)> y = Poison.encode(mtime)
{:error, {:invalid, {{2019, 3, 16}, {23, 47, 17}}}}
iex(4)> 

Jonathan.

JSON has no concept of tuples. Only JS arrays (Elixir lists).

So you’ll have to convert your data structures to be JSON-friendly.

3 Likes

Ah. OK, thanks.

It’s worth noting that if you have a DateTime instead, Poison will know how to JSONify that into an ISO 8601 string. Just note that on the decode side, you’ll get a string and have to convert it back to a DateTime yourself.

1 Like