ELM 0.19解码中的8个以上地图

时间:2018-12-21 13:58:51

标签: json elm

我有带有默认值的标志解码器。

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")

如何添加更多字段?我有一个包含10个字段的JSON对象。

1 个答案:

答案 0 :(得分:11)

我建议使用andMap中的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")

但是还有其他选项,例如elm-json-decode-pipelinea new experimental APIandMap确实非常简单明了,可以根据需要与mapN一起使用并切换到DAX