我正在尝试转换这个 json
{ "date": [2018, 2, 3] }
进入这个模型
type alias MyModel = { date: Date }
我知道如何将其解码为列表
decoder =
decode MyModel (field "date" (list int))
但我不知道如何将解码器链接在一起。
最佳答案
您可以使用 Json.Decode.index
提取已知索引处的值。您需要索引 0、1 和 2 处的值,然后您可以将它们转换为字符串以供 Date.fromString
使用。像这样:
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
)
您可以像这样使用解码器:
decoder =
decode MyModel (field "date" dateDecoder)
关于elm - 在 Elm 中将整数数组解码为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48600176/