将嵌套的json解码并压平成Elm记录

时间:2018-02-12 04:45:35

标签: 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)

1 个答案:

答案 0 :(得分:7)

<强>更新

通常情况下,我在发布此消息后立即找到答案。我查看了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)