Encode optional string in Elm
Asked Answered
C

2

5

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
Cantus answered 15/7, 2020 at 16:43 Comment(0)
A
8

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
Autosome answered 15/7, 2020 at 19:33 Comment(0)
A
4

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
  
Anuran answered 16/7, 2020 at 10:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.