LoginSignup
12
1

【TIPS】マップ:文字列キーとアトムキーの相互変換

Last updated at Posted at 2023-12-06

この記事は、Elixir Advent Calendar 2023 シリーズ8 の11日目です

昨日は、私で 「【TIPS】マップ:文字列キーとアトムキーの相互変換」 でした


【本コラムは、5分で読め、10分で試せます】

piacere です、ご覧いただいてありがとございます :bow:

Elixirのマップって、文字列キーとアトムキーの2種類、定義があり、これを入れ替えるのが面倒なこと、ありませんか?

TIPSとしてまとめておきました … Elixirの様々な書き方のトレーニングにもなると思います

文字列キーからアトムキーへ変換

%{"first" => 1, "last" => 10, "step" => 2} |> Map.new(fn {k, v} -> {String.to_atom(k), v} end)
%{"first" => 1, "last" => 10, "step" => 2} |> Map.new(&{String.to_atom(elem(&1, 0)), elem(&1, 1)})
for {k, v} <- %{"first" => 1, "last" => 10, "step" => 2}, into: %{}, do: {String.to_atom(k), v}
%{"first" => 1, "last" => 10, "step" => 2} |> Jason.encode! |> Jason.decode!(keys: :atoms)

アトムキーから文字列キーへ変換

%{first: 1, last: 10, step: 2} |> Map.new(fn {k, v} -> {Atom.to_string(k), v} end)
%{first: 1, last: 10, step: 2} |> Map.new(&{Atom.to_string(elem(&1, 0)), elem(&1, 1)})
for {k, v} <- %{first: 1, last: 10, step: 2}, into: %{}, do: {Atom.to_string(k), v}
%{first: 1, last: 10, step: 2} |> Jason.encode! |> Jason.decode!

明日は、私で 「【TIPS】構造体とマップの相互変換」 です

12
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
1