wolfiton
How to use get_in to retrieve Item name from [%{"id" => "1849", "name" => "Reuben"}]
Hi everyone,
How can i retrieve the name from a structure like this?
%{"id" => "1570", "name" => "Croque Monsieur"}
My test looks like this
describe "GetMenuItems.gql == matching" do
test "Should return all Menu items (1 of them)" do
result = query_gql(variables: %{"matching" => "reu"})
assert {:ok, %{data: %{"MenuItems" => menu_items}}} = result
IO.inspect(menu_items)
assert length(menu_items) == 1
assert menu_items == [%{"name" => "Reuben", "id" => 1471}]
end
end
What i tried:
name = get_in(menu_items, [:name])
name = get_in(result, [:data, "MenuItems", "name"])
So can someone explain to me the correct way to do this?
Thanks
Most Liked
benwilson512
"name" is a string, :name is an atom.
On a larger note though, I really don’t recommend using get_in like this to test API responses. The reason is that if things don’t go as you expect, either because you have a bug in your test code, or because your API isn’t returning what you expect, the error messages don’t tell you anything.
I always test my GraphQL apis using a combination of = and == eg:
assert {:ok, %{data: %{"MenuItems" => menu_items}}} = result
assert menu_items == [%{"name" => "Reuben", "id" => 1471}]
This is so much better than using get_in because if result doesn’t match, the error message will tell you what result actually is. Then if the name isn’t "Reuben", once again the failure message will show you the whole thing.
Eiji
If you have a list of menu items then you need to use Access.at/1.
ityonemo
Access.at is zero indexed.
ityonemo
Maps are special in pattern matching; you can ignore id as well by doing this:
%{"name"=>"foo"} = my_map
The difference being Ben’s match enforces the presence of an id field but not its value, and mine enforces neither.
Aduril
As @Eiji mentions a list would require Access.at/1
The other way would be to use get_in with a function as key (see
Kernel — Elixir v1.19.3 )
If you always expect exactly one result at this point you can also do it like this:
Hope I helped you ![]()








