Elm JSON 对象解码器数组

Elm JSON Decoder Array of Objects

我正在用 elm 做一个 http 请求,我的响应是一个对象数组。每个对象如下

obj = {
    title: "Some Title",
    words: [ "word1", "word2", "word3", "word4" ]
}

到目前为止,这是我的解码器:

type alias ThisRes = List ResObj


type alias ResObj =
    title: String 
    words: List String


decoded : Decoder ThisRes
decoded = 
    decode ThisRes

我似乎无法正确使用解码器,如能提供任何帮助,我们将不胜感激。

obj =
    """
    {
        "title": "Some Title",
        "words": [ "word1", "word2", "word3", "word4" ]
    }
    """


type alias ResObj =
    { title : String, words : List String }


objDecoder =
    map2 ResObj
        (at [ "title" ] string)
        (at [ "words" ] (list string))


headingFrom : Result String ResObj -> String
headingFrom result =
    case result of
        Ok resobj ->
            resobj.title

        Err reason ->
            toString reason


main =
    h1 [] [ text <| headingFrom <| decodeString objDecoder obj ]

分解:

  • obj 只是代表一些 JSON 的字符串,以说明示例。
  • 您定义 ResObj 类型别名,并为其获取类型构造函数。现在您可以通过调用 ResObj "MyTitle" ["word1", "wordb", "wordFightingMongooses"].
  • 创建 ResObj
  • objDecoder 是一个有助于将 JSON 解码为 ResObj 的值。它调用 map2,它接受一个类型构造函数,然后是两个解码的 JSON 字段。 (at ["title"] string) 表示 "turn the value at title in the JSON into a string",您可以猜出下一行是做什么的。所以这最终评估为 ResObj "SomeTitle" ["word1", "word2", "word3", "word4"] 并创造你的价值。
  • 在我们的 main 中,我们有表达式 decodeString objDecoder objdecodeString 获取一个解码器值和一个 JSON 字符串,并查看它是否可以对其进行解码。但它 return ResObj 本身不是——因为解码可能会失败,它 return 是一个结果。
  • 因此我们必须使用我们的函数 headingFrom 来处理该结果。如果解码成功,我们的结果将是 Ok resobj,我们终于可以使用 resobj 了。如果失败,它将是 Err reason.