0

我正在尝试解析 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 行为的模块运行此代码。

4

1 回答 1

0

您解析的 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它时,您会遇到异常,因为它是一个列表,而不是地图。

于 2022-02-11T16:07:50.983 回答