4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ElixirAdvent Calendar 2023

Day 10
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

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

Last updated at Posted at 2024-01-01

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


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

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

Elixirのマップは、キーが、アトムと文字列の2種類使えます

アトムキーのマップ
iex> user_a = %{id: :id000, name: "hoge", weight: 49}
iex> user_a.name
"hoge"
iex> user_a[:name]
"hoge"
iex> user_a |> Map.put(:name, "piacere")
%{id: :id000, name: "piacere", weight: 49}
文字列キーのマップ
iex> user_s = %{"id" => :id000, "name" => "hoge", "weight" => 49}
iex> user_s["name"]
"hoge"
iex> user_s |> Map.put("name", "piacere")
%{"id" => :id000, "name" => "piacere", "weight" => 49}

ただし、この2種類の間に互換性が無いため、扱いに困ることがありますので、相互変換の技をまとめておきます

文字列キーマップをアトムキーマップに変換

Map.new + String.to_atom

iex> user_s |> Map.new(&{String.to_atom(elem(&1, 0)), elem(&1, 1)})
%{id: :id000, name: "hoge", weight: 49}

iex> user_s |> Map.new(fn {k, v} -> {String.to_atom(k), v} end)
%{id: :id000, name: "hoge", weight: 49}

for + String.to_atom

iex> for {k, v} <- user_s, into: %{}, do: {String.to_atom(k), v}
%{id: :id000, name: "hoge", weight: 49}

Jason.encode! + Jason.decode! ※ただし要注意

アトムのバリューが、文字列に変化してしまうので注意

iex> user_s |> Jason.encode! |> Jason.decode!(keys: :atoms)
%{id: :id000, name: "hoge", weight: 49}

文字列キーマップをアトムキーマップに変換

Map.new + Atom.to_string

iex> user_a |> Map.new(fn {k, v} -> {Atom.to_string(k), v} end)
%{"id" => :id000, "name" => "hoge", "weight" => 49

iex> user_a |> Map.new(&{Atom.to_string(elem(&1, 0)), elem(&1, 1)})
%{"id" => :id000, "name" => "hoge", "weight" => 49}

for + Atom.to_string

iex> for {k, v} <- user_a, into: %{}, do: {Atom.to_string(k), v}
%{"id" => :id000, "name" => "hoge", "weight" => 49}

Jason.encode! + Jason.decode! ※ただし要注意

アトムのバリューが、文字列に変化してしまうので注意

iex> user_a |> Jason.encode! |> Jason.decode!
%{"id" => "id000", "name" => "hoge", "weight" => 49}
4
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?