Lets say you have a Tagged Union type in your system like Direction

type Direction = North | South | East | West

It is possible that you would want to encode that to json and decode it back from JSON. The standard JSON encoders and decoders won’t do it. So to doe the encoding and decoding we need to make it work.


stringToDirection : String -> Decoder Direction
stringToDirection str =
    case str of
        "North" -> succeed North
        "South" -> succeed South
        "East"  -> succeed East
        "West"  -> succeed West
        _       -> fail ("Value " ++ str ++ "Is not a direction")

decodeDirection : Decoder Direction
decodeDirection = string|> andThen stringToDirection

This can be seen to work with these tests.


all : Test
all =
    describe "Decode Direction"
        [
         test "North" <|
              \() ->
            Expect.equal (Result.Ok North) <| decodeString decodeDirection  "\"North\""
        , test "South" <|
              \() ->
            Expect.equal (Result.Ok South) <| decodeString decodeDirection  "\"South\""
        , test "East" <|
              \() ->
            Expect.equal (Result.Ok East) <| decodeString decodeDirection  "\"East\""
        , test "West" <|
              \() ->
            Expect.equal (Result.Ok West) <| decodeString decodeDirection  "\"West\""
        , test "No Direction" <|
              \() ->
            Expect.equal Nothing <| Result.toMaybe<| decodeString decodeDirection  "\"xxxx\""
        ]

Want more content like this? Sign up for my mailing List!

And you can get the entire source for this example in this gist