Turn a JSON string Into Typed Data in Elm

InstructorMurphy Randle

Share this video with your friends

Send Tweet

Turning JSON strings into types, also known as JSON Decoding is an important part of using Elm. It allows the programmer to use json-encoded data while staying completely aware of when the JSON might not match the programmer's expectations, all without throwing a run-time error! This lesson will show the viewer how to turn a simple JSON object into an analogous Elm record and use it to render some content to the screen.

Cristian Gabbanini
~ 5 years ago

Hi, I don't know precisely since when, but in recent versions Elm has been providing some helpers which could simplify JSON decoding (at least for structures of low/average complexity).

So, if anybody is stumbling upon this lesson, I'd suggest to have a look here: https://guide.elm-lang.org/effects/json.html#combining-decoders

In fact, we could just use the Json.Decode module (https://package.elm-lang.org/packages/elm-lang/core/5.1.1/Json-Decode) and do the following:

personDecoder :  Decoder Person
personDecoder = 
  map3 Person
        (field "name" string)
        (field "email" string)
        (field "favouriteNumber" int)

Thanks for this lesson! I am a newbie to Elm and every info is precious to me 🏅