在 Elm 中编码可选字符串

Encode optional string in Elm

如果 Maybe String 有具体值,我想将其编码为 string,如果它是 Nothing,我想将其编码为 null

目前,我使用辅助函数 encodeOptionalString myStr 来获得所需的效果。我想知道是否有更像 Elm 的方法来做到这一点。我真的很喜欢elm-json-decode-pipeline的API,它允许我写Decode.nullable Decode.string来解码。

encodeOptionalString : Maybe String -> Encode.Value
encodeOptionalString s =
    case s of
        Just s_ ->
            Encode.string s_

        Nothing ->
            Encode.null

您可以自己将其归纳为 encodeNullable 函数:

encodeNullable : (value -> Encode.Value) -> Maybe value -> Encode.Value
encodeNullable valueEncoder maybeValue =
    case maybeValue of
        Just value ->
            valueEncoder value

        Nothing ->
            Encode.null

或者,如果您想要一个稍微短一些的临时表达式:

maybeString
|> Maybe.map Encode.string
|> Maybe.withDefault Encode.null

elm-community/json-extra 包中有您想要的方法。

maybe : (a -> Value) -> Maybe a -> Value
Encode a Maybe value. If the value is Nothing it will be encoded as null