Encode optional string in Elm

Viewed 559

I would like to encode a Maybe String to string if it has a concrete value, or null if it's Nothing.

At the moment, I use a helper function encodeOptionalString myStr to get the desired effect. I was wondering if there's a more Elm-like way of doing this. I really like the API of elm-json-decode-pipeline that allows me to write Decode.nullable Decode.string for decoding.

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

        Nothing ->
            Encode.null
2 Answers

You could generalize this into an encodeNullable function yourself:

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

        Nothing ->
            Encode.null

Or if you want a slightly shorter ad hoc expression:

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

The package elm-community/json-extra has exactly the method you desire.

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