在 elixir 中使用 Poison 获取地图中的错误解析列表

Getting error parsing List in map with Poison in elixir

我正在尝试解析 api 查询,但在以下代码中出现错误:

apiUrl = "https://api.trivia.willfry.co.uk/questions?limit=1"
HTTPoison.start()
{:ok, req} = HTTPoison.get(apiUrl)

# Parses the request.
json = Poison.decode!(req.body)
parsed = Map.fetch!(json, :root)

错误说:

(BadMapError) expected a map, got: [%{"category" => "Film and TV", "correctAnswer" => "\"A martini. Shaken, not stirred.\"", "id" => 29312, "incorrectAnswers" => ["\"Elementary, my dear Watson.\"", "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"", "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"", "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"", "\"Made it, Ma! Top of the world!\"", "\"I have always depended on the kindness of strangers.\""], "question" => "Which of these quotes is from the film 'Goldfinger'?", "type" => "Multiple Choice"}]   
:erlang.map_get(:root, [%{"category" => "Film and TV", "correctAnswer" => "\"A martini. Shaken, not stirred.\"", "id" => 29312, "incorrectAnswers" => ["\"Elementary, my dear Watson.\"", "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"", "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"", "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"", "\"Made it, Ma! Top of the world!\"", "\"I have always depended on the kindness of strangers.\""], "question" => "Which of these quotes is from the film 'Goldfinger'?", "type" => "Multiple Choice"}])
(triv 0.1.0) lib/mix/tasks/request.ex:15: Mix.Tasks.Request.run/1
(mix 1.13.3) lib/mix/task.ex:397: anonymous fn/3 in Mix.Task.run_task/3
(mix 1.13.3) lib/mix/cli.ex:84: Mix.CLI.run_task/2

我 运行 这段代码来自实现 Mix.Task 行为的模块。

您解析的 JSON 似乎是列表,而不是地图:

[
  %{
    "category" => "Film and TV",
    "correctAnswer" => "\"A martini. Shaken, not stirred.\"",
    "id" => 29312,
    "incorrectAnswers" => ["\"Elementary, my dear Watson.\"",
     "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"",
     "\"Go ahead, make my day.\"", "\"I am a golden god!\"", "\"Toga! Toga!\"",
     "\"We rob banks.\"", "\"E.T. phone home.\"", "\"Here's Johnny!\"",
     "\"Made it, Ma! Top of the world!\"",
     "\"I have always depended on the kindness of strangers.\""],
    "question" => "Which of these quotes is from the film 'Goldfinger'?",
    "type" => "Multiple Choice"
  }
]

当您尝试对其调用 Map.fetch!/2 时,出现异常,因为它是一个列表,而不是地图。