Decode an array of integers as Date in Elm

I am trying to convert this json

{ "date": [2018, 2, 3] }

into this model

type alias MyModel = { date: Date }

I know how to decode it to a list

decoder = 
   decode MyModel (field "date" (list int))

but I can't figure out how to combine decoders together.

+4
source share
1 answer

You can use Json.Decode.indexto pull values ​​by known indexes. You will need the values ​​at indexes 0, 1, and 2, and then you can convert them to a string for use in the Date.fromStringfollowing way:

import Date exposing (Date)
import Html exposing (Html, text)
import Json.Decode exposing (..)

dateDecoder : Decoder Date
dateDecoder =
    let
        toDateString y m d =
            String.join "-" (List.map toString [ y, m, d ])
    in
    map3 toDateString
        (index 0 int)
        (index 1 int)
        (index 2 int)
        |> andThen
            (\str ->
                case Date.fromString str of
                    Ok date ->
                        succeed date

                    Err err ->
                        fail err
            )

You can use the decoder as follows:

decoder = 
    decode MyModel (field "date" dateDecoder)
+5
source

Source: https://habr.com/ru/post/1693115/


All Articles