
TL;DR
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
Start elm-repl and import Json.Decode module with three primitive type decoder functions: int, string and bool. decodeString is a function that does decoding of raw JSON string. Parameters are input type and raw JSON string.
Primitives
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 Int.
Data Structures
Let’s add data structures list and field and decode field name and a list of int. Full JSON.Decode feature set could be found on official documentation.
Remember
- decoding JSON must be safe. This could be a security risk for your application
- Consult the documentation for all Decode features.