在Elm中解析嵌套的JSON [英] Parsing nested JSON in Elm

查看:82
本文介绍了在Elm中解析嵌套的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况

-- 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

I am trying to parse a JSON so formed

{
  "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)

它不起作用,我正在获得

It does not work, I am getting

Comments不公开Model.

您如何公开type alias?

如何为示例设置Decoder?

推荐答案

已更新为Elm 0.18

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

To expose Comments.Model, make sure your Comments.elm file exposes all types and functions like this:

module Comments exposing (..)

或者,您可以公开如下类型和函数的子集:

Or, you can expose a subset of types and functions like this:

module Comments exposing (Model)

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

There are a few problems with your decoders. First off, to match your JSON, you're going to need a record type alias that exposes a single posts list Posts.

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

您没有评论用的解码器.看起来像这样:

You are missing a decoder for comments. That will look like this:

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

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

I'm going to rename your decoder function to postDecoder to avoid ambiguity. Now you can fix the comments decoder line by using the new commentDecoder.

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:

Lastly, we can fix decoderColl by using that posts wrapper type (PostListContainerModel) we created earlier:

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

这篇关于在Elm中解析嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆