I’m super new to elm and I am currently having problem with parsing a HTTP response, which is in the form of JSON. It looks something like this:
[
{
“title”:“Songs, Merry and Sad”,
“author”:“John Charles McNeill”
},
{
“title”:“The Ambassadors”,
“author”:“Henry James”
}
]
Basically, my web app sends a request to my backend, which responds with a JSON file as such. I have created this type alias:
type alias Book =
{ title : String
, author : String}
In addition, here is my HTTP request:
search : Model -> Cmd Msg
search model =
Http.post
{ url = “0.0.0.0:5000/search”
, body = Http.multipartBody [Http.stringPart “keyword” model.keyword]
, expect = Http.expectJson GotSearch searchDecoder
}
And here is my decoder:
searchDecoder : Decoder (List Book)
searchDecoder =
Json.Decode.list bookDecoder
bookDecoder : Decoder Book
bookDecoder =
map2 Book
(field “title” string)
(field “author” string)
Despite clearly stating expectJSON in my HTTP request, I get this BadBody error with the following message:
Problem with the value at json[0]:\n\n {\n “title”: “Songs, Merry and Sad”,\n “author”: “John Charles McNeill”\n }\n\nExpecting a STRING
I’m not sure what’s going on here. Help would be greatly appreciated since I’m super stuck.
Hm. Your code looks fine to me, I can’t see the mistake.
I’d try to Debug this code by simplifying it: e.g. replace the Book datatype with a Json.Decode.Value for now, and see whether it parses the list successfully. Then try only parsing one key or so.
You’ll likely have further questions. For tighter feedback loops I can recommend the beginners or general channel on the elm slack: https://elmlang.herokuapp.com/
Can you try posting the raw response of the request to 0.0.0.0:5000/search? You can find the response text in the developer tools of your browser in the “network” tab after your app made the request.
Paste the exact raw JSON output from your API in there (the sample variable) and see it you get Ok or Err. I tried to guess what your raw JSON is, and if I got it right your decoders seem to work!
Once you know your decoders work you can continue with Http. Hopefully breaking the task up in small steps will help you succeed.