The following examples can be tested on https://ellie-app.com/m9vmQ8NcMc/0.
import Html exposing (..)
import Json.Decode
payload =
"""
[ { "bark": true, "tag": "dog", "name": "Zap", "playful": true }
, { "whiskers": true, "tag" : "cat", "name": "Felix" }
, {"color": "red", "tag": "tomato"}
]
"""
-- OUR MODELS
type alias Dog =
{ bark: Bool
, name: String
, playful: Bool
}
type alias Cat =
{ whiskers: Bool
, name: String
}
-- OUR DIFFERENT ANIMALS
type Animal
= DogAnimal Dog
| CatAnimal Cat
| NoAnimal
main =
Json.Decode.decodeString decoder payload
|> toString
|> text
decoder =
Json.Decode.field "tag" Json.Decode.string
|> Json.Decode.andThen animalType
|> Json.Decode.list
animalType tag =
case tag of
"dog" ->
Json.Decode.map3 Dog
(Json.Decode.field "bark" Json.Decode.bool)
(Json.Decode.field "name" Json.Decode.string)
(Json.Decode.field "playful" Json.Decode.bool)
|> Json.Decode.map DogAnimal
"cat" ->
Json.Decode.map2 Cat
(Json.Decode.field "whiskers" Json.Decode.bool)
(Json.Decode.field "name" Json.Decode.string)
|> Json.Decode.map CatAnimal
_ ->
Json.Decode.succeed NoAnimal