【问题标题】:Parsing nested JSON in Elm在 Elm 中解析嵌套的 JSON
【发布时间】:2016-03-04 16:59:04
【问题描述】:

我有这种情况

-- this is in post.elm
type alias Model =
  { img : String
  , text : String
  , source : String
  , date : String
  , comments : Comments.Model
  }

-- this is in comments.elm
type alias Model =
  List Comment.Model

-- this is in comment.elm
type alias Model =
  { text : String
  , date : String
  }

我正在尝试解析这样形成的 JSON

{
  "posts": [{
    "img": "img 1",
    "text": "text 1",
    "source": "source 1",
    "date": "date 1",
    "comments": [{
      "text": "comment text 1 1",
      "date": "comment date 1 1"
    }]
  }
}

这是我的Decoder

decoder : Decoder Post.Model
decoder =
  Decode.object5
    Post.Model
    ("img" := Decode.string)
    ("text" := Decode.string)
    ("source" := Decode.string)
    ("date" := Decode.string)
    ("comments" := Decode.list Comments.Model)

decoderColl : Decoder Model
decoderColl =
  Decode.object1
    identity
    ("posts" := Decode.list decoder)

它不起作用,我得到了

Comments 不会暴露 Model。

如何公开type alias?

如何为我的示例设置Decoder?

【问题讨论】:

    标签: json elm


    【解决方案1】:

    编辑:更新到 Elm 0.18

    要公开Comments.Model,请确保您的 Comments.elm 文件公开所有类型和函数,如下所示:

    module Comments exposing (..)
    

    或者,您可以像这样公开一部分类型和函数:

    module Comments exposing (Model)
    

    您的解码器存在一些问题。首先,为了匹配您的 JSON,您将需要一个记录类型别名,该别名公开一个 posts 列表帖子。

    type alias PostListContainerModel =
      { posts : List Post.Model }
    

    您缺少 cmets 的解码器。看起来像这样:

    commentDecoder : Decoder Comment.Model
    commentDecoder =
      Decode.map2
        Comment.Model
        (Decode.field "text" Decode.string)
        (Decode.field "date" Decode.string)
    

    我要将您的 decoder 函数重命名为 postDecoder 以避免歧义。现在您可以使用新的commentDecoder 修复comments 解码器行。

    postDecoder : Decoder Post.Model
    postDecoder =
      Decode.map5
        Post.Model
        (Decode.field "img" Decode.string)
        (Decode.field "text" Decode.string)
        (Decode.field "source" Decode.string)
        (Decode.field "date" Decode.string)
        (Decode.field "comments" (Decode.list commentDecoder))
    

    最后,我们可以使用我们之前创建的帖子包装类型 (PostListContainerModel) 来修复 decoderColl:

    decoderColl : Decoder PostListContainerModel
    decoderColl =
      Decode.map
        PostListContainerModel
        (Decode.field "posts" (Decode.list postDecoder))
    

    【讨论】:

    • 你能看看这个问题吗?我再次坚持这一点,对我希望的结果更进一步stackoverflow.com/questions/35845299/…
    • Elm 新手:小心,这个答案包含 0.18 之前的语法。特别是,:= 已变为 field,objectX 已变为 mapX。见Upgrading to 0.18 / Renamed functions in core
    • 还有module Comments (Model) where变成了module Comments exposing (Model)
    • 感谢 Ronan 和 farmio - 我已经更新了 Elm 0.18 的答案
    • 嗯...上限为map8。如果我们得到一个包含 50 个字段的 json 对象呢?
    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 2017-08-25
    • 1970-01-01
    • 2021-07-27
    • 2015-02-20
    • 2018-09-12
    相关资源
    最近更新 更多