1

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?

N. Sola
  • 340
  • 4
  • 11

1 Answers1

7

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!
Gazler
  • 83,029
  • 18
  • 279
  • 245