将嵌套 json 解码并展平为 Elm 记录

Decode and flatten nested json into an Elm record

我刚开始学习 Elm,但遇到了障碍。从这个很棒的社区寻求帮助。

我正在寻找解码嵌套的 json 并将特定的嵌套值拉入 elm 记录。

json 来源如下所示:

 {
    "id": 672761,
    "modified": "2018-02-12T00:53:04",
    "slug": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.",
    "type": "post",
    "link": "https://awesomelinkhere.com",
    "title": {
        "rendered": "Sed posuere consectetur est at lobortis."
    },
    "content": {
        "rendered": "Nulla vitae elit libero, a pharetra augue.",
    },
    "excerpt": {
        "rendered": "Donec sed odio dui.",
    }
}

我想将 title.renderedcontent.rendered 拆分到模型中的一个字段中,模型如下所示:

type alias Post =
    { id : Int
    , published : String
    , title : String
    , link : String
    , slug : String
    , excerpt : String
    }

我天真的解码器看起来像这样

postDecoder : Decoder Post
postDecoder =
    Decode.map6 Post
        (field "id" Decode.int)
        (field "modified" Decode.string)
        (field "title" Decode.string)
        (field "link" Decode.string)
        (field "slug" Decode.string)
        (field "excerpt" Decode.string)

更新

正如通常发生的那样,我一发布就找到了答案。我查看了 Json.Decode documentation 并偶然发现了 at 函数

我的工作解码器现在看起来像这样

postDecoder : Decoder Post
postDecoder =
    Decode.map6 Post
        (field "id" Decode.int)
        (field "modified" Decode.string)
        (at [ "title", "rendered" ] Decode.string)
        (field "link" Decode.string)
        (field "slug" Decode.string)
        (at [ "excerpt", "rendered" ] Decode.string)