Skip to content

Instantly share code, notes, and snippets.

@stepheneb
Last active May 18, 2019 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stepheneb/f8f83cb1b5ac3d7f4522f82c77dba5fc to your computer and use it in GitHub Desktop.
Save stepheneb/f8f83cb1b5ac3d7f4522f82c77dba5fc to your computer and use it in GitHub Desktop.
Decoding an Elm type from a json object
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