I am trying to parse an api query but I get an error in the following code:
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)
The error says:
(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
I am running this code from a module which implements the Mix.Task behaviour.
Your parsed JSON appears to be a list, not a map:
[
%{
"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"
}
]
When you try calling Map.fetch!/2
on it, you're getting an exception because it's a list, not a map.