Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.