在 Elixir 中映射 JSON 值

RN9*_*N92 4 elixir elixir-poison jsonparser

我已经使用 Posion.decode 解析了以下 JSON!

json = %{"color-Black|size:10" => 
    %{"attributes" => %{"color" => "Black","size" => "11"},    
      "isAvailable" => true,      
    "pricing" => %{"standard" => "$415.00", "sale" => 415}}, 
 "color|size-EU:9.5" => 
    %{"attributes" => %{"color" => "Black","size" => "11"},    
      "isAvailable" => true,      
    "pricing" => %{"standard" => "$415.00", "sale" => 415}}}
Run Code Online (Sandbox Code Playgroud)

我想映射它,但随着节点元素中的文本发生变化,我无法获取 JSON 元素。到目前为止我已经尝试过了。

Enum.map(json , fn(item) ->
%{
  color: item.attributes["color"],                 
  size: item.attributes["size"],
  price: item.pricing["standard"] * 100,
  isAvailable: item.isAvailable
 }
end)
Run Code Online (Sandbox Code Playgroud)

但是这段代码给出了一些与访问相关的错误。

Ale*_*kin 5

在映射映射时,迭代的键值对作为元组到达映射器{key, value}

\n\n\n\n
Enum.map(json, fn {_, %{"attributes" => attributes,\n                        "isAvailable" => isAvailable,\n                        "pricing" => pricing}} ->\n  %{\n    color: attributes["color"],\n    size: attributes["size"],\n    price: pricing["standard"],\n    isAvailable: isAvailable\n   }\nend)\n\n#\xe2\x87\x92 [\n#    %{color: "Black", isAvailable: true, price: "$415.00", size: "11"},\n#    %{color: "Black", isAvailable: true, price: "$415.00", size: "11"}\n# ]\n
Run Code Online (Sandbox Code Playgroud)\n\n

在这里,我们对映射器中的值使用就地模式匹配,以简化匹配器本身的代码,并使其在输入错误的情况下不易出错。

\n