在 Elm 中将整数数组解码为日期
Decode array of integers as Date in Elm
我正在尝试转换这个 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)
我正在尝试转换这个 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)