我有这种情况
-- 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
}
Run Code Online (Sandbox Code Playgroud)
我试图解析一个如此形成的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"
}]
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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)
Run Code Online (Sandbox Code Playgroud)
它没有用,我得到了
Comments没有曝光Model.
你怎么曝光type alias?
我如何设置Decoder我的例子?
Cha*_*ert 11
编辑:更新为Elm 0.18
要公开Comments.Model,请确保您的Comments.elm文件公开所有类型和函数,如下所示:
module Comments exposing (..)
Run Code Online (Sandbox Code Playgroud)
或者,您可以公开类型和函数的子集,如下所示:
module Comments exposing (Model)
Run Code Online (Sandbox Code Playgroud)
解码器有一些问题.首先,要匹配您的JSON,您将需要一个记录类型别名,公开单个posts列表帖子.
type alias PostListContainerModel =
{ posts : List Post.Model }
Run Code Online (Sandbox Code Playgroud)
你缺少一个评论解码器.这将是这样的:
commentDecoder : Decoder Comment.Model
commentDecoder =
Decode.map2
Comment.Model
(Decode.field "text" Decode.string)
(Decode.field "date" Decode.string)
Run Code Online (Sandbox Code Playgroud)
我要重命名你的decoder函数postDecoder以避免歧义.现在,您可以comments使用新的修复解码器行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))
Run Code Online (Sandbox Code Playgroud)
最后,我们可以decoderColl使用PostListContainerModel我们之前创建的post wrapper type()来修复:
decoderColl : Decoder PostListContainerModel
decoderColl =
Decode.map
PostListContainerModel
(Decode.field "posts" (Decode.list postDecoder))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2774 次 |
| 最近记录: |