In the previous post, we added an Elm JSON library. Today we will learn how to use the JSON decoder. This post is part of the functional language series, and it is based on a remarkable book, Programming Elm Build Safe and Maintainable Front-End Applications by Jeremy Fairbank.
JSON In REPL
elm-repl and import
Json.Decode module with three primitive type decoder functions:
decodeString is a function that does decoding of raw
JSON string. Parameters are input type and raw
Let’s start with
int decoder. We successfully decoded “42” and got an error for “true”.
Note the type annotation: `Result.Result String Int`. This is from Elm core library:
type Result error value
= Ok value
| Err error
error is a string that describes an error, while the value is in our case Elm
Let’s add data structures
field and decode field
name and a
int. Full JSON.Decode feature set could be found on official documentation.
- decoding JSON must be safe. This could be a security risk for your application
- Consult the documentation for all Decode features.