Search code examples
jsonelm

More than 8 map in ELM 0.19 decode


I have flags decoder with default values.

flagsDecoder : Decode.Decoder Params
flagsDecoder =
    Decode.map8 Params
        (Decode.field "field1" (Decode.string) |> (Decode.withDefault) "1")
        (Decode.field "field2" (Decode.string)   |> (Decode.withDefault) "2")
        (Decode.field "field3" (Decode.string)   |> (Decode.withDefault) "3")
        (Decode.field "field4" (Decode.string) |> (Decode.withDefault) "4)
        (Decode.field "field5" (Decode.string)  |> (Decode.withDefault) "5")
        (Decode.field "field6" (Decode.int) |> (Decode.withDefault) 6)
        (Decode.field "field7" (Decode.string)    |> (Decode.withDefault) "7")
        (Decode.field "field8" (Decode.string)   |> (Decode.withDefault) "8")

How can i add more fields? I have a JSON object with 10 fields.


Solution

  • I would recommend using andMap from elm-community/json-extra:

    flagsDecoder : Decode.Decoder Params
    flagsDecoder =
        Decode.succeed Params
            |> Decode.andMap (Decode.field "field1" (Decode.string) |> (Decode.withDefault) "1")
            |> Decode.andMap (Decode.field "field2" (Decode.string)   |> (Decode.withDefault) "2")
            |> Decode.andMap (Decode.field "field3" (Decode.string)   |> (Decode.withDefault) "3")
            |> Decode.andMap (Decode.field "field4" (Decode.string) |> (Decode.withDefault) "4")
            |> Decode.andMap (Decode.field "field5" (Decode.string)  |> (Decode.withDefault) "5")
            |> Decode.andMap (Decode.field "field6" (Decode.int) |> (Decode.withDefault) "6")
            |> Decode.andMap (Decode.field "field7" (Decode.string)    |> (Decode.withDefault) "7")
            |> Decode.andMap (Decode.field "field8" (Decode.string)   |> (Decode.withDefault) "8")
    

    But there are also other options like elm-json-decode-pipeline and a new experimental API. andMap is really simple and straight-forward though, to use along with and to switch to from mapN if needed.