如何用变量 属性 类型解码 json

How to decode a json with a variable property type

我有以下 JSON:

{
    "items": [
        {
            "level": 1,
            "displayValue": "das",
            "dataValue": "das"
        },
        {
            "level": 2,
            "displayValue": "das",
            "dataValue": {
                "name": "some name",
                "scope": "some scope"
            }
        }
    ]
}

以及以下类型:

type alias Item = 
    { level: Int
    , displayValue: String
    , dataValue: DataValue
    }

type alias KeyValue =
    { name: String
    , scope: String
    }

type DataValue
    = Value String
    | Key KeyValue

我如何为 dataValue 属性 编写解码器,因为它可以是两种完全不同的类型?

您可以使用 oneOf:

import Json.Decode as JD

dataValueDecoder : JD.Decoder DataValue
dataValueDecoder =
    JD.oneOf
        [ JD.map Value JD.string 
        , JD.map Key keyValueDecoder
        ]

keyValueDecoder : JD.Decoder KeyValue
keyValueDecoder =
    JD.map2 KeyValue
        (JD.field "name" JD.string)
        (JD.field "scope" JD.string)