Elm 如何解码具有可变属性类型的json

Elm 如何解码具有可变属性类型的json,elm,Elm,我有以下JSON: { "items": [ { "level": 1, "displayValue": "das", "dataValue": "das" }, { "level": 2, "displayValue": "das", "dataValue": {

我有以下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属性可以是两种完全不同的类型,我如何为其编写解码器?

您可以使用:

导入Json。解码为JD
dataValueDecoder:JD.Decoder DataValue
数据值解码器=
法学博士
[JD.map值JD.string]
,JD.map密钥keyValueDecoder
]
keyValueDecoder:JD.Decoder KeyValue
键值译码器=
JD.map2键值
(JD.field“name”JD.string)
(JD.field“scope”JD.string)