Generating pipeline and applicative decoders with json2elm
2021-05-18

I’ve added a few features to json2elm.

In addition to plain elm/json decoders, it can now also generate applicative and pipeline decoders. It also generates the required imports based on the chosen decoder type. You can also choose between noun-based and verb-based function names for decoders and encoders.

Applicative decoders take advantage of the andMap function from elm-community/json-extra and look like this:

accountDecoder : Json.Decode.Decoder Account
accountDecoder = 
    Json.Decode.succeed Account
        |> Json.Decode.Extra.andMap (Json.Decode.field "id" Json.Decode.int)
        |> Json.Decode.Extra.andMap (Json.Decode.field "prefs" accountPrefsDecoder)
        |> Json.Decode.Extra.andMap (Json.Decode.field "user" accountUserDecoder)

Pipeline decoders rely on the NoRedInk/elm-json-decode-pipeline package and look like this:

accountDecoder : Json.Decode.Decoder Account
accountDecoder = 
    Json.Decode.succeed Account
        |> Json.Decode.Pipeline.required "id" Json.Decode.int
        |> Json.Decode.Pipeline.required "prefs" accountPrefsDecoder
        |> Json.Decode.Pipeline.required "user" accountUserDecoder

I’ve also added imports to the generated code, so for example for pipeline decoders you will get a preamble like this:

import Json.Decode
import Json.Encode
import Json.Decode.Pipeline


-- Required packages:
-- * elm/json
-- * NoRedInk/elm-json-decode-pipeline

Finally, there are two naming styles you can choose from for the functions: noun-based and verb-based. If you use nouns, you will get names like accountDecoder and encodedAccount versus decodeAccount and encodeAccount when using verbs. I am partial to noun function names for the reason that in functional programs, we are describing what the transformations of the data are, rather than how they are done.

Would you like to dive further into Elm?
📢 My book
Practical Elm
skips the basics and gets straight into the nuts-and-bolts of building non-trivial apps.
🛠 Things like building out the UI, communicating with servers, parsing JSON, structuring the application as it grows, testing, and so on.
Practical Elm