在Elixir中将Base64字符串转换为映射 [英] Convert a Base64 string into a map in Elixir

查看:157
本文介绍了在Elixir中将Base64字符串转换为映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Elixir解码包含JSON的Base64字符串. 我使用以下功能:

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

Base.url_decode64(string)

Base.url_decode64(string)

但是,此函数返回一个字符串.特别是:

However, this function returns a string. In particular:

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

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

问题在于此结构应该是映射而不是字符串,因为否则我将无法访问JSON字段.

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?

推荐答案

您需要使用JSON库.有几种,一种是常用的一种是毒物(在

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!

这使用 Poison.decode!/2 函数.

每当我使用时,我都希望将其别名为JSON,以便在我的整个代码中都没有对Poison的引用:

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!

这篇关于在Elixir中将Base64字符串转换为映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆