Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Encoding a map in Elixir using Poison

Tags:

json

elixir

I'm trying to parse my map into a json string, how would i do that using poison?

I've tried the following.

iex(19)> test = %{"api_key" => "sklfjklasfj"}
%{"api_key" => "sklfjklasfj"}
iex(20)> Poison.Encoder.encode(test, [])
[123, [[34, ["api_key"], 34], 58, [34, ["sklfjklasfj"], 34]], 125]

What i would expect was

"{"api_key": "sklfjklasfj"}"
like image 624
MartinElvar Avatar asked Feb 27 '15 10:02

MartinElvar


1 Answers

I realised poison was returning a char_list, which can be casted to a string like so.

iex(27)> to_string Poison.Encoder.encode(test, [])
"{\"api_key\":\"sklfjklasfj\"}"

As of October 2017 (Poison v3), the code would be

iex(27)> to_string Poison.encode_to_iodata!(test, [])
"{\"api_key\":\"sklfjklasfj\"}"

or simply

iex(27)> Poison.encode!(test, [])
"{\"api_key\":\"sklfjklasfj\"}"

without the to_string call.

like image 85
MartinElvar Avatar answered Oct 03 '22 01:10

MartinElvar