This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In


    Automatically Generating JSON Decoders in Elm

    Enrico BuonannoEnrico Buonanno

    To a certain extent, the definition of record types and decoders that mirror your JSON data can be automated. Json to Elm is an online app that can help you to get started translating your JSON into Elm; you can then take the output and fine tune it.



    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 as we've seen, decoding JSON into Elm does take a bit of work. If you have lots of JSON objects with lots of fields, it can get a bit tedious. Some of this work can be automated. To help you with this, there's an online app called json-to-elm. Let me copy this JSON that we've been using, and let me go to the JSON to Elm app.

    00:25 You can see here, you have two screens. On the left you paste your JSON, and on the right, you get some Elm code. Then here on top, it says, "Enter a top-level alias." This would be user for us. Now, you can see what happens here on the right. We get a type alias user with ID email is premium, a translation of the fields in our JSON.

    00:48 Notice that what you get on the right side is the type aliases, user, user profile, which is this nest record, and then, you get the decoders for these types. You also get the encoders, so functions that translate from Elm into JSON. Also, notice that there's a few different options. There's the original decoder type that uses the map X functions.

    01:13 You can use pipeline, which uses the pipeline library that we've also seen. If you need to write a lot of decoders, then taking this as a starting point might be a useful option. This is especially true if you don't need to do any transformation in the data. In other words, if you want the structure of your Elm objects to closely mirror the structure of your JSON.

    01:36 For example, in our decoders, we've done a lot of transformations. We've flattened this user profile object into the main user type. We've decoded this string ID into an int. We've changed each premium to a dedicated membership type, and so on. Of course, the more customization you want to do as part of decoding, the less this sort of automated decoding is useful.

    02:02 The other thing to keep in mind, of course, is that here it assumes that all the fields are required. Of course, you will need to make changes for any fields that are optional or nullable...