解析时如何将字符串 JSON 值膨胀到对象?

How do I inflate a string JSON value to an object when parsing?

我有一条从 JSON:

解析的记录
import Json.Decode exposing (..)
import Json.Decode.Pipeline exposing (..)

type alias Article = {
    pubDate: String
}

articleDecoder : Decoder Article
articleDecoder =
    decode Article
        |> required "pubDate" string

现在,如果我想对 pubDate 使用 Date 而不是原始字符串,我该如何更改代码以使用 [=14= “膨胀” JSON 值]?

看起来这行得通:

type alias Article = {
    pubDate: Date
}

articleDecoder : Decoder Article
articleDecoder =
    decode Article
        |> required "pubDate" pubDateDecoder

pubDateDecoder : Decoder Date.Date
pubDateDecoder =
    string |> andThen (\s ->
        case Date.fromString s of
            Err e -> fail e
            Ok d -> succeed d
        )

术语

Elm 词汇表中没有 inflate 这样的术语。

解码一个JSON字符串或JavaScritpt对象。

Elm 中没有对象。

所以你想将带有格式化日期的字符串解码为Date类型的数据结构。

实施

截至今天(0.18.0)Date.fromString from core is proven to be unreliable.

您应该使用 Date.Extra.fromIsoString from justinmimbs/elm-date-extra 模块从 ISO 8601 进行更可靠的日期解析。

为清楚起见,我保留了命名空间。

dateDecoder : Decoder Date
dateDecoder =
    Json.Decode.string
        |> Json.Decode.andThen
            (\s ->
                case Date.Extra.fromIsoString s of
                    Err e ->
                        Json.Decode.fail e

                    Ok d ->
                        Json.Decode.succeed d
            )