Introduction to Elm, v2

Decoding JSON Solution

Richard Feldman

Richard Feldman

Vendr, Inc.
Introduction to Elm, v2

Check out a free preview of the full Introduction to Elm, v2 course

The "Decoding JSON Solution" Lesson is part of the full, Introduction to Elm, v2 course featured in this preview video. Here's what you'd learn in this lesson:

Richard walks through the solution to the Decoding JSON exercise.

Preview
Close

Transcript from the "Decoding JSON Solution" Lesson

[00:00:00]
>> Richard Feldman: So we have just the one to do here. Let's start by taking a look at how sort of the existing version looks. So we have this global feed. Everything in here say it needs decoding. Hey, we now have the article that I posted, [LAUGH] great, from the previous exercise.

[00:00:14]
[COUGH] Well, it also needs decoding. So all of these things are relying on the same decoder for metadata, which currently has everything as hardcoded. So essentially, let's convert these. So metadata is a type alias that is defined up here. So it's got description which is a string, title which is a string, a list of tags, favorite id, favorites count and createdAt, and createdAt is the only one that's filled in with required.

[00:00:42]
So let's just go down the line. [COUGH] So the first one we're gonna need is a required description and that one is a string. Then we're gonna need another required one, in fact all these are gonna be required, so title, title is also a string. Then we have tagList,

[00:01:01]
>> Richard Feldman: Which is not a string but a list of strings. And so we're gonna call the list function inside the json.decode module, and pass it string decoder so it turns that from a single string decoder to a decoder of list of strings. Then we've got favorited, which is a bullion, that will just be bull.

[00:01:22]
And finally we have favoritesCount,
>> Richard Feldman: Which is an int, okay.
>> Richard Feldman: Let's see. Yeah, order matters. These must be decoded in the same order the order of the fields in 'type alias Metadata' above. So let's just double check that we got those in the right order, description, title, tagList, favorited, favoritesCount, and createdAt.

[00:01:49]
Looks good, let's rebuild, that worked. Let's refresh, go to the global feed and hey, we got article titles again. Including, this excellent piece that I wrote here, which I all suggest you read afterwards, because, I think it's really got a lot to say.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now