Skip to content

Instantly share code, notes, and snippets.

@focusaurus
Created December 5, 2016 00:26
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save focusaurus/1085181366a6399414f0b0049ece3750 to your computer and use it in GitHub Desktop.
Save focusaurus/1085181366a6399414f0b0049ece3750 to your computer and use it in GitHub Desktop.
Decode JSON string enum into elm union type
module A exposing (..)
import Json.Decode as JD
import Json.Encode as JE
type alias User =
{ id : Int
, theme : Theme
}
type Theme
= Light
| Dark
userDecoder =
(JD.map2 User
( JD.field "id" JD.int )
( JD.field "theme" decodeTheme )
)
-- Can't figure out how to make a custom Json.Decoder.Decoder a
decodeTheme toDecode =
let
valueDe =
JD.decodeString JD.string toDecode
in
case valueDe of
Ok name ->
if (String.toLower name) == "light" then
Light
else
Dark
Err msg ->
Dark
@ohri-anurag
Copy link

Great example!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment