Convert a Base64 string into a map in Elixir

寵の児 提交于 2019-12-13 01:34:22

问题


I am using Elixir to decode a Base64 string which contains a JSON. I use the following function:

Base.url_decode64(string)

However, this function returns a string. In particular:

"{\"algorithm\":\"HMAC-SHA256\",\"app_data\":\"1\",\"issued_at\":1452249105,\"page\":{\"id\":\"1051194981579510\",\"admin\":true},\"user\":{\"country\":\"se\",\"locale\":\"en_GB\",\"age\":{\"min\":21}}}"

The problem is that this structure should be a map instead of a string because otherwise I can't access the JSON fields.

The question is: how can I convert this string into a map? Or: how can I treat this string as a map and access anyway the single fields?


回答1:


You need to use a JSON library. There are several, one commonly used one is Poison (there are others on hex):

string |> Base.url_decode64 |> Poison.decode!

This uses the Poison.decode!/2 function.

Whenever I use I like to alias it as JSON so that I don't have references to Poison throughout my code:

alias Poison, as: JSON
string |> Base.url_decode64 |> JSON.decode!


来源:https://stackoverflow.com/questions/34675044/convert-a-base64-string-into-a-map-in-elixir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!