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

Autoplay

    Decode large JSON Objects into Elm with `elm-decode-pipeline`

    Enrico BuonannoEnrico Buonanno

    An alternative to decode objects with more than 8 fields is to use elm-decode-pipeline. This package also uses the applicative approach. For an explanation of the applicative approach in general, see this lesson in my course of form validation

    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 another popular library for decoding large objects is elm-decode-pipeline. Let's start by installing that. The author is NoRedInk, and the package is called, "elm-decode--pipeline." Then in our file, we need to import json.decode.pipeline. We're going to use a number of different functions, decode, optional, optional at, required, and required at.

    00:48 We'll see what these do in just a moment. Let me go to my decoder. Instead of succeed, you use decode. In reality, decode is exactly the same of succeed, it's just a matter of readability. The approach is still the same that we're putting the user function into a decoder that succeeds. Then, rather than this operator, we use the normal pipe like this.

    01:14 Then, here is where we would use one of these functions. For required fields, instead of field, we say required. Let me remove these extra parentheses here. For nested fields that are required, we say required at. Then for optional fields, we use optional or optional at. In this case, we have a nested field, this would be optional at.

    01:51 The API is slightly different, there's an additional parameter where we can specify the value to use if the field is not found. In this case, we want nothing. Our decoder for gender, decodes to a gender, whereas our field is of type maybe gender, we need to map this with just. If this decoder succeeds with a map that with just, and if it fails, we'll get nothing.

    02:22 Then this last field, let's assume this is optional so that we demonstrate using the optional function, as well. We're decoding this as a list of notifications. We use empty list as a default value.

    02:37 If I save, this works, and we still get the object correctly decoded as before. You can see that with decode pipeline we still get the same benefits, namely we don't have to change the name of map X function, and we can combine an arbitrary number of the decoders...

    Discuss

    Discuss