Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In


    Handle nullable and optional Fields when Decoding JSON into Elm

    Enrico BuonannoEnrico Buonanno

    Use nullable to define a decoder that can handle a JSON null value. Some APIs will leave a field out altogether; you can define a decoder for such an optional field with maybe.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:00 How can you handle nullable fields? Imagine, for example, that our users are not required to disclose their gender, so this may well be null. Elm, of course, doesn't have null, but uses maybe instead. In our model, this would be a maybe of gender.

    00:21 If I save that now, you can see that this doesn't compile, because my types don't line up. I'm providing a gender where the user function is expecting a maybe of gender.

    00:31 For nullable fields, there is a nullable function that takes a decoder and transforms it into an optional decoder, if you like. Now, you can see that this works, and we have gender of nothing. If I change that to say female, then the gender has gone to just female.

    00:56 Some JSON APIs will have null for optional fields, but some APIs will leave the field out altogether. If we try running this, you see we get an error decoding the JSON. What we have is not really a nullable value, but rather a completely absent field.

    01:12 In this case, we need a slightly different variation, and that is to use a function called maybe. What this is saying is that maybe we have this field. Let me save that, and you can see now that gender is nothing. If I add the gender back in, let's make it male again, then we have just male as expected.