8

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"}"
2
  • 4
    Note you can also use Poison.encode/1 and Poison.decode/1 without touching Poison.Encoder. Commented Feb 27, 2015 at 13:44
  • Thank you whatyouhide :) Commented Feb 27, 2015 at 14:27

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It's not a char_list, which is just a flat list of code points; it's an IO list, which can be arbitrarily nested. You can send them directly as file or socket IO, and they'll get flattened when needed. See dev.af83.com/2012/01/16/erlang-iolist.html, for example.
Note now in the newest version of Poison you'd use encode_to_iodata! instead of just encode.
Or just use encode! and drop the to_string call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.