【问题标题】:Decode and flatten nested json into an Elm record将嵌套的 json 解码并展平为 Elm 记录
【发布时间】:2018-07-22 05:20:12
【问题描述】:

我刚开始学习 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)

【问题讨论】:

  • 将您的更新添加为答案并将其标记为已解决。它使其他人以后更容易找到这些信息。
  • 更新了更新!

标签: elm


【解决方案1】:

更新

正如通常发生的那样,我一发布这个就找到了答案。我查看了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)

【讨论】:

  • 在深思熟虑形成问题后立即回答自己的问题让我感到困惑。我现在拥有 elm 解码所需的一切。太棒了。
猜你喜欢
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 2017-08-25
  • 2020-05-02
  • 1970-01-01
相关资源
最近更新 更多