The simplest approach would be to use Json.Decode.oneOf along with
Json.Decode.map:

dataValueDecoder : Json.Decode.Decoder DataValue
dataValueDecoder =
    Json.Decode.oneOf
        [ Json.Decode.string |> Json.Decode.map Val
        , ... decode your KeyType record ...  |> Json.Decode.map Key
        ]

(Note that if you have control over the JSON format, for more complicated
cases, it's often best to add a "type" field to your JSON, so you can
decode the "type" field first, and then you Json.Decode.andThen to switch
off of the type, which would be more performant if you have lots of cases,
but in your example probably wouldn't be worth the complexity.)


On Wed, Nov 15, 2017 at 11:14 AM, Thiago Temple <vin...@gmail.com> wrote:

> I have situation where I have to a jso object similar to this
>
> { "level": 1, "displayValue": "some text", "dataValue": "a string with
> the value" }
>
> { "level": 1, "displayValue": "some text", "dataValue": { "name": "xxx",
> "scope": "xxxx" } }
>
> Both cases for dataValue are valid, it can either have a string or an
> object.
>
> I have created types as such:
>
> type DataValue
>   = Val String
>   | Key KeyType
>
> type alias KeyType =
>  { name: String, source: String }
>
> type alias MyObj =
>  { level: Int, displayValue: String, dataValue: DataValue}
>
> How can I decode dataValue for MyObj?
>
> Thanks
>
> --
> You received this message because you are subscribed to the Google Groups
> "Elm Discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to elm-discuss+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups "Elm 
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elm-discuss+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to