elm-community / json-extra

Convenience functions for working with Json.
http://package.elm-lang.org/packages/elm-community/json-extra/latest
MIT License
37 stars 16 forks source link

Add Json.Encode.Extra.maybe #4

Closed hendore closed 7 years ago

hendore commented 7 years ago

Encode Maybe values as null if Nothing.

Without Json.Encode.Extra.maybe

encoder : Person -> Json.Encode.Value
encoder person =
    let
        age =
            case person.age of
                Nothing ->
                    Json.Encode.null

                Just val ->
                    Json.Encode.int val

        avatar =
            case person.avatar of
                Nothing ->
                    Json.Encode.null

                Just val ->
                    Json.Encode.string val
    in
        Json.Encode.object
            [ ( "name", Json.Encode.string person.name )
            , ( "email", Json.Encode.string person.email )
            , ( "age", age )
            , ( "avatar", avatar )
            ]

With Json.Encode.Extra.maybe

encoder : Person -> Json.Encode.Value
encoder { name, email, age, avatar } =
        Json.Encode.object
            [ ( "name", Json.Encode.string name )
            , ( "email", Json.Encode.string email )
            , ( "age", Json.Encode.Extra.maybe Json.Encode.int age )
            , ( "age", Json.Encode.Extra.maybe Json.Encode.string avatar )
            ]
mgold commented 7 years ago

Seems useful and reasonable. Would the "without" code benefit from Maybe.map encoder >> Maybe.withDefault Json.Encode.null?

lukewestby commented 7 years ago

I think it's reasonable to include, it seems like a super common usecase and the parity with 0.18's Decode.nullable is nice

@hendore would you mind changing the doc heading from # Oddly Shaped Values to # Maybe?

hendore commented 7 years ago

@mgold Nice, thats a very clever alternative.

@lukewestby Updated the heading, I just copied the # Oddly Shaped Values from the core Decode module. https://github.com/elm-lang/core/blob/master/src/Json/Decode.elm#L35