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


    Decode Nested JSON Objects into Flat Elm Records

    Enrico BuonannoEnrico Buonanno

    Your Elm model may mirror the structure of your JSON exactly, but updating nested records in Elm is somewhat tedious, so you may sometimes choose to keep Elm types "flatter" then their JSON counterparts. Using the at decoder you can decode nested JSON values, and use them in the construction of a flat Elm record.



    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:01 Let's imagine that the definition of our JSON changes so that the fields gender and dateOfBirth are no longer at top level, but are nested within a field called profile. If I save now, of course, the coding breaks, because we specified that we should look for these fields, gender and dateOfBirth, but these are no longer found.

    00:32 One way would be to change our model for user and have a nested record called profile, but nested records in Elm are not so much fun. I would rather keep these fields here at top level, as they were. I can use this by changing the field with a different decoder that is called at.

    00:54 At is very similar to field, but rather than taking a single string that's the name of the field, it takes a list of strings. In this case, it's profile, gender, and it will be the same here. This list of strings allows you to drill down inside a nested JSON object.

    01:20 What this is saying is take the value that you find in this nested field, profile, dateOfBirth, and then, we can construct our user. As you can see, our decoder is now fixed. We have a nested JSON object, and we're decoding it into a flat Elm record.