Last active
May 18, 2019 20:08
-
-
Save stepheneb/f8f83cb1b5ac3d7f4522f82c77dba5fc to your computer and use it in GitHub Desktop.
Decoding an Elm type from a json object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module DecodeElmType exposing (Status(..), json, statusDecoder, statusFieldToStringDecoder, statusFromStringDecoder) | |
import Json.Decode exposing (..) | |
type Status | |
= Queued | |
| Started | |
| Complete | |
json = | |
""" { "status": "Started" } """ | |
statusFieldToStringDecoder : Decoder String | |
statusFieldToStringDecoder = | |
field "status" string | |
statusFromStringDecoder : Result Error String -> Maybe Status | |
statusFromStringDecoder result = | |
case result of | |
Err _ -> | |
Nothing | |
Ok value -> | |
case value of | |
"Queued" -> | |
Just Queued | |
"Started" -> | |
Just Started | |
"Complete" -> | |
Just Complete | |
_ -> | |
Nothing | |
statusDecoder : String -> Maybe Status | |
statusDecoder str = | |
decodeString statusFieldToStringDecoder str |> statusFromStringDecoder | |
-- > import DecodeElmType exposing (..) | |
-- > statusDecoder json | |
-- Just Started : Maybe Status | |
-- > statusDecoder """ { "status": "Empty" } """ | |
-- Nothing : Maybe Status |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment