我试图解析一个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
时,您会得到一个异常,因为它是一个列表,而不是映射。