1_5.JSON - ohr486/ErlangElixirFestHandsOn GitHub Wiki
1_5.JSON
jsonを取り扱うライブラリとして、poisonがあります。
poisonの組み込み指定
プロジェクトにライブラリ(今回はpoision)を組み込むには、mix.exs
のdepsにライブラリ情報を以下の様に追記します。
defp deps do
[
{:poison, "~> 3.1"} # これを追加、 {ライブラリ名, バージョン指定}
]
end
poisonのインストール
mix.exs
にライブラリ情報を追記したら、mix deps.get
で指定したライブラリをインストールできます。
インストールしたライブラリはプロジェクトディレクトリ直下のdepsディレクトリの中に保存されます。
# ls
README.md config lib mix.exs mix.lock test
# mix deps.get
Resolving Hex dependencies...
Dependency resolution completed:
poison 3.1.0
* Getting poison (Hex package)
# ls
README.md config deps lib mix.exs mix.lock test
#
jsonのパース
jsonのパースは、Poison.decode(文字列)
で行えます。
# iex -S mix
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Interactive Elixir (1.6.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Poison.decode("{\"hoo\":123,\"bar\":234}")
{:ok, %{"bar" => 234, "hoo" => 123}}
iex(2)> Poison.decode!("{\"hoo\":123,\"bar\":234}")
%{"bar" => 234, "hoo" => 123}
iex(3)>
Poison.decode
が{:ok, パース結果のMap}
を返却するのに対して、Poison.deocde!
はパース結果のみを返却します。