将如下所示的api响应解析为所需格式的最佳方法是什么?通常我会使用Enum.reduce,但因为有嵌套在地图中的列表,我不知道如何构建累加器。
api_resonse =
[
%{"meta" => %{"labels" => %{"app" => "api-app"}},
"spec" => %{"container" => [%{"resources = %{}, image" => "gcr"}]},
"status" =>[%{"type" => "updated", "state" => %{"running"}}]
},
%{"meta" => %{"labels" => %{"app" => "user-app"}},
"spec" => %{"container" => [%{"resources = %{}, image" => "dcr"}]},
"status" =>[%{"type" => "updated", "state" => %{"running"}}]
},
%{"meta" => %{"labels" => %{"app" => "admin-app"}},
"spec" => %{"container" => [%{"resources = %{}, image" => "gcr"}]},
"status" =>[%{"type" => "updated", "state" => %{"failed"}}]
}
]
expected output =
%{
"api-app" => %{ "image" => "gcr", "state" => "running"},
"user-app" => %{ "image" => "dcr", "state" => "running"},
"admin-app" => %{ "image" => "gcr", "state" => "failed"}
}
答案 0 :(得分:2)
您可以使用Enum.map/2
和模式匹配。有一些语法错误,所以我稍微改变了输入。
api_response =
[
%{"meta" => %{"labels" => %{"app" => "api-app"}},
"spec" => %{"container" => [%{"resources" => %{}, "image" => "gcr"}]},
"status" =>[%{"type" => "updated", "state" => "running"}]
},
%{"meta" => %{"labels" => %{"app" => "user-app"}},
"spec" => %{"container" => [%{"resources" => %{}, "image" => "dcr"}]},
"status" =>[%{"type" => "updated", "state" => "running"}]
},
%{"meta" => %{"labels" => %{"app" => "admin-app"}},
"spec" => %{"container" => [%{"resources" => %{}, "image" => "gcr"}]},
"status" =>[%{"type" => "updated", "state" => "failed"}]
}
]
api_response
|> Enum.map(fn
%{"meta" => %{"labels" => %{"app" => app}},
"spec" => %{"container" => [%{"resources" => %{}, "image" => image}]},
"status" => [%{"type" => "updated", "state" => state}]} ->
{app, %{"image" => image, "state" => state}}
end)
|> Map.new
|> IO.inspect
输出:
%{"admin-app" => %{"image" => "gcr", "state" => "failed"},
"api-app" => %{"image" => "gcr", "state" => "running"},
"user-app" => %{"image" => "dcr", "state" => "running"}}