預解碼欄位並根據解碼的值解碼其餘欄位

可以在 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