Elm Radio Episode 4 - JSON Decoders

Episode 4 is out! We hope you find it useful. I think we lay out some useful points if you’re getting started with JSON decoders. And we get into some best practices and concepts for more advanced Elm developers as well.

7 Likes

I liked the part about optional fields and the where to put the Json.Decode.maybe. Here’s an easy way to remember how to do it: Use Json.Decode.Extra.optionalNullableField. Hot take: Json.Decode.maybe is never useful.

4 Likes

Great point @lydell!

You’re right that if you use Json.Decode.maybe it will cover up some cases that you may not have intended to. I didn’t really consider this, but you’re absolutely right!

import Json.Decode as Decode

""" {"temperatureInF": 86} """ |> Decode.decodeString (Decode.maybe (Decode.field "temperatureInF" Decode.int))
--> Ok (Just 86)

""" {"temperatureInF": 86.14} """ |> Decode.decodeString (Decode.maybe (Decode.field "temperatureInF" Decode.int))
--> Ok Nothing

In many cases, if you’re allowing the field to be null or absent, you would still want to know if it’s present but the decoder fails. I bet that’s tripped some people up. I wish I was aware of Json.Decode.Extra.optionalNullableField when we recorded that episode! I’ll update the show notes with a reference to this, though Update: I updated the show notes! :smile:

2 Likes

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