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 a JSON String and Convert it to an Elm `Int`

    Enrico BuonannoEnrico Buonanno

    A good use case for andThen is if we need to convert a JSON string into an Int as part of the decoding process.

    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 look at another example of using andThen. Imagine we have an API where the ID always comes as a string. Imagine this is a legacy API. We cannot touch it, and we know that the ID will always be an int, but it's sent across as a string.

    00:18 On our client application, we still want to have it as an int. We want a conversion from string to int to always happen as part of decoding. Here, we can no longer use int as a decoder. Rather, we would use string, and then we would need to convert it to an int. We could use andThen with string.toInt. We need to use andThen, because the function on the right side might fail.

    00:48 This is not exactly right, because on the left side, we have a decoder, and the function on the right side returns a result. What we would need to do is, if this returns an OK result, then we want to return a decoder that succeeds, and if it returns an error, would return a decoder that fails.

    01:07 We could do this with a pattern-matching expression. Instead, I'd like to use a helper function. To do this, I will need to install a package. It's elm-community/json-extra. This is a library that has a number of useful functions for working with JSON. Let me import json.decode.extra. The function I want is fromResult.

    01:47 I can use this here. The idea is that first I transform the string into a result of int, and then I transform the results into a decoder. I forgot to type "exposing." Now, it's fixed. You can see that here we have the string 123, but this value is then converted to an int as part of the decoding.

    02:19 This example also illustrates how you should use andThen whenever the function on the right side might fail. In reality, I use this fromResult function from json.decode.extra, but there is even the function parseInt, which does what we want to start with. If I replace all of this with parseInt, that works just the same.

    Discuss

    Discuss