elixir:如何计算字符串中列表项的数量

时间:2016-08-17 08:46:20

标签: elixir elixir-poison

我尝试使用Poison

解码以下json字符串
iex(1)> fetch(1)
{:ok,
 "{\"name\":\"Anabela\",\"surname\":\"Neagu\",\"gender\":\"female\",\"region\":\"Romania\"}"}
iex(2)> fetch(2)
{:ok,
 "[{\"name\":\"Juana\",\"surname\":\"Su├írez\",\"gender\":\"female\",\"region\":\"Argentina\"},{\"name\":\"ðíðÁÐÇð│ðÁð╣\",\"surname\":\"ðƒð╗ð¥Ðéð¢ð©ð║ð¥ð▓\",\"gender\":\"male\",\"region\":\"Russia\"}]"}

执行fetch(1) |> decode_response不会起作用,尽管它适用于param严格支持1。

我确实有以下错误

10:07:52.663 [error] GenServer Newsequence.Server terminating
** (BadMapError) expected a map, got: {"gender", "female"}
    (stdlib) :maps.find("gender", {"gender", "female"})
    (elixir) lib/map.ex:145: Map.get/3
    lib/poison/decoder.ex:49: anonymous fn/3 in Poison.Decode.transform_struct/4
    (stdlib) lists.erl:1262: :lists.foldl/3
    lib/poison/decoder.ex:48: Poison.Decode.transform_struct/4
    lib/poison/decoder.ex:24: anonymous fn/5 in Poison.Decode.transform/4
    (stdlib) lists.erl:1262: :lists.foldl/3
    lib/poison/decoder.ex:24: Poison.Decode.transform/4 Last message: {:getpeople, 1} State: {[], #PID<0.144.0>}

我的功能如下:

def decode_response({:ok, body}) do
    Poison.decode!(body, as: [%Personne{}])
end

我认为param等于1,函数应该是

   def decode_response({:ok, body}) do
        Poison.decode!(body, as: %Personne{})
    end

我终于认为在我的fetch函数给出的字符串中计算元组是一个好主意,并使用一个guard来选择使用哪个decode_response,但我不知道如何使用。

有人可以指出我正确的方向吗?

此致

皮埃尔

2 个答案:

答案 0 :(得分:1)

您可以先使用Poison.decode!/1解码到原生地图/列表,然后计算as:的相关值,然后最后使用本机数据结构调用Poison.Decoder.decode/2来执行此操作结构解码成:

def decode_response({:ok, body}) do
  parsed = Poison.decode!(body)
  as =
    cond do
      is_map(parsed) -> %Personne{}
      is_list(parsed) -> [%Personne{}]
    end
  Poison.Decoder.decode(parsed, as: as)
end

演示:

defmodule Personne do
  defstruct [:name, :surname, :gender, :region]
end

defmodule Main do
  def main do
    f1 = {:ok, "{\"name\":\"Anabela\",\"surname\":\"Neagu\",\"gender\":\"female\",\"region\":\"Romania\"}"}
    f2 = {:ok, "[{\"name\":\"Juana\",\"surname\":\"Su├írez\",\"gender\":\"female\",\"region\":\"Argentina\"},{\"name\":\"ðíðÁÐÇð│ðÁð╣\",\"surname\":\"ðƒð╗ð¥Ðéð¢ð©ð║ð¥ð▓\",\"gender\":\"male\",\"region\":\"Russia\"}]"}

    f1 |> decode_response |> IO.inspect
    f2 |> decode_response |> IO.inspect
  end

  def decode_response({:ok, body}) do
    parsed = Poison.decode!(body)
    as =
      cond do
        is_map(parsed) -> %Personne{}
        is_list(parsed) -> [%Personne{}]
      end
    Poison.Decoder.decode(parsed, as: as)
  end
end

Main.main

输出:

%{"gender" => "female", "name" => "Anabela", "region" => "Romania",
  "surname" => "Neagu"}
[%{"gender" => "female", "name" => "Juana", "region" => "Argentina",
   "surname" => "Suárez"},
 %{"gender" => "male", "name" => "ðíðÁÐÇð│ðÁð╣",
   "region" => "Russia",
   "surname" => "ðƒð╗ð¥Ðéð¢ð©ð║ð¥ð▓"}]

答案 1 :(得分:0)

它有点天真,但它会保存第二次解析JSON:

if (body |> String.trim_leading() |> String.starts_with?("[")) do
  Poison.decode!(body, as: [%Personne{}])                    
else                                                       
  Poison.decode!(body, as: %Personne{})                      
end

请注意,如果您使用的是Elixir 1.2或更低版本,则您希望使用String.lstrip/1代替String.trim_leading/1

另一种方法是将其解码为地图,使用String.to_existing_atom/1转换密钥,然后使用Kernel.struct/2转换为结构。

  def decode_response({:ok, body}) do
    body |> Poison.decode!() |> string_map_struct(Personne)
  end

  defp string_map_struct(entry, module) do
    params =
      entry
      |> Enum.map(fn {key, val} ->
        key = to_existing_atom(key)
        {key, val}
      end)
      |> Enum.into(%{})
    struct(module, params)
  end

  defp to_existing_atom(key) do
    try do
      String.to_existing_atom(key)
    rescue
      ArgumentError -> key
    end
  end