Last active
July 28, 2016 22:29
-
-
Save klaftertief/e77b8954f0d74f7307f311a0d26dc504 to your computer and use it in GitHub Desktop.
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 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