In the previous post, we learned about the practical usage of the Elm pipe operator. Today we will use elm-json-decode-pipeline package to safely decode JSON from a String. 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.
Decode A Object
Using just Elm-REPL and Elm JSON Decode and Pipeline modules, we are going to write a simple JSON decoder that, as input, takes JSON string.
decodeString is a function that does heavy work of decoding. With
string function, decodes JSON String into Elm String. You can recognize JSON string by symbols
bool function decodes JSON boolean value into Elm boolean.
succeed the function returns
Ok with the input parameter.
required function from
Pipeline the module is exciting. It would decode input value, while we need to set input value JSON type.
Do not forget to start
elm repl from the picshare folder. Otherwise, Pipeline will not be found.
Next, we need a record that describes our data. We have
softwareTester function with
automation attributes. In the end, we create
softwareTesterDecoder on successful decoding, returns
softwareTeser. For successful decoding, the decoder requires in JSON string two attributes,
name is String, while
automation is bool. We first made three unsuccessful decodings (Karlo was not terminated with a closing
" and JSON
True is the wrong value) and the final try was successfull.
- the purpose of JSON.Pipeline module
- how to use
|>to create a JSON decoder.