Skip to content

Instantly share code, notes, and snippets.

@klaftertief
Last active July 28, 2016 22:29
Show Gist options
  • Save klaftertief/e77b8954f0d74f7307f311a0d26dc504 to your computer and use it in GitHub Desktop.
Save klaftertief/e77b8954f0d74f7307f311a0d26dc504 to your computer and use it in GitHub Desktop.
module Decoder exposing (..)
import Json.Decode as Decode exposing ((:=))
import Json.Decode.Extra as Decode exposing ((|:))
type Foo
= Bar String Int
| Baz String Int
decode : Decode.Decoder Foo
decode =
"type" := Decode.string `Decode.andThen` decodeType
-- ("type" := Decode.string) `Decode.andThen` decodeType
decodeType : String -> Decode.Decoder Foo
decodeType tipe =
let
base =
case tipe of
"bar" ->
Decode.succeed Bar
|: ("name" := Decode.string)
"baz" ->
Decode.succeed Baz
|: ("name" := Decode.string)
_ ->
Decode.fail ("Type `" ++ tipe ++ "` not supported")
in
base
|: ("count" := Decode.int)
barJson : String
barJson =
"""
{
"type": "bar",
"name": "MyBar",
"count": 123
}
"""
decoded : Result String Foo
decoded =
Decode.decodeString decode barJson
_ =
Debug.log "decoded?" decoded
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment