Decoding a JSON with no field names

Oh I knew I would run into JSON Decoder issues. This one seems so innocuous and simple but I have been banging my head on this for a few hours now so I decided to swallow my pride and ask.

I had no issues with decoding my JSON when it came in with some field names { word : “whatever”, category : “whatever” } but now I switched to an API that just delivers me a JSON with no field names – just a simple { “whatever” }.

How the hell do I decode this?
I am still new so going through the pains of switching into the FP mindset a bit, and I feel like this will be a good hurdle to overcome, but I just couldn’t do it so I am reaching out for help. Any resources you think might help too are always welcome. The guide is great but stops a little short in addressing this (at least from what I can tell - I am sure its there I just cannot decipher it yet)

Here is the Decoder I was using:

wordDecoder : Decoder String
wordDecoder =
Decode.field “word” Decode.string

for just a simple…

fetchWord : Cmd Msg
fetchWord =
Http.get
{ url = “https://random-word-form.herokuapp.com/random/animal
, expect = Http.expectJson NewPhrase wordDecoder
}

Thank you in advance!!!

If your API really returns

   { "whatever" }

that is not valid JSON and you won’t be able to parse it with Json.Decode.

If you get

    [ "whatever" ]

(note [ and ] instead of { and }) what you have is a JSON list. You can use Json.Decode.index (with an integer index instead of a field name) just like you used Json.Decode.field before. You can also use Json.Decode.list or Json.Decode.array to get the whole list at once.

If you get

   "whatever"

(no braces at all), Json.Decode.string is what you want.

If you are really getting invalid JSON, I would try to get the people responsible for the API to overthink their decision. If you can’t, you will need to write your own parser, maybe using the elm/parser package.

4 Likes

Okay, thank you @eike , I got it. You were right it was [“Whatever”] and not {“Whatever”} and the Decode.index did it for me.

This was simply an exercise in me learning piece by piece how to read these docs. Still trying to make that mindset transition, and seeing the types still throws me off. So when I see the field signature and the index signature be the same, them being types still is not registering with me and even thinking that “Oh, that means I can use a Decode.index option too”

I think I will get there but little stumbling blocks like are probably dime a dozen so thanks for helping me out :smile:

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.