thitemple
thitemple

Reputation: 6059

How to decode a json with a variable property type

I have the following JSON:

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

And the following types:

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

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

type DataValue
    = Value String
    | Key KeyValue

How would I write a decoder for the dataValue property since it can be of two completly different types?

Upvotes: 1

Views: 149

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

You can use 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)

Upvotes: 3

Related Questions