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

Autoplay

    Decode JSON into Elm Lists and Arrays

    Enrico BuonannoEnrico Buonanno

    The list function takes a decoder for a given type and creates a decoder for a list of values of that type. The array function works similarly but produces an Elm Array.

    elmElm
    Code

    Code

    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
    Transcript

    Transcript

    Instructor: 00:01 Let's imagine we have a list of notifications that we want to display for our user. To keep things simple initially, let me model this as a list of strings. Let me add some modifications to my JSON. Now, I need to change my decoder accordingly. User now has an additional field, so it takes five arguments.

    00:35 Let me change this to map five. Here, I need to add a new field. The name is notifications, and the decoder to use here, if this was a single string, then I would use string. Because this is a list of strings, I will use list of string. This is a function that takes a decoder for any given type, and returns a decoder for a list of that type.

    01:00 Let me save, and indeed, you can see that we have a list of strings for the notifications field. Now, let me make this slightly more complex. Instead of assuming that a notification is just a string, let's assume we have a more complex object like this. Each notification has a title and a message.

    01:18 Here in my user type alias, this would now be a list of notification. I need to define a type alias notification. Now, let me create a decoder for a single notification. I'm going to call it notification, and for objects for use, map X, as usual. Map two, since it's just two fields. We have the field title as a string and the field message, it's also a string.

    02:09 Now, our field notifications is no longer a list of strings, but it's a list of notification. It works. If you look at the decoded JSON, we have notification as an array of records, each of which has a title and a message. Decoding into an array is almost the same as decoding into a list. Instead of the list function, you would use array.

    02:38 This implies that your model has an array. You would need to import this here. This works, and it looks very much the same. Of course, you should choose to use a list or an array depending on how you're going to access the data, but it is a good idea once you decide which data structure you need to build that structure as part of JSON decoding.

    Discuss

    Discuss