2016-03-04 112 views
2

我这种情况解析嵌套的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

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

回答

8

编辑:更新后榆树0.18

为了揭露Comments.Model,请确保您的Comments.elm文件公开所有类型和功能是这样的:

module Comments exposing (..) 

或者,你可以公开的一个子集类型和功能如下:

module Comments exposing (Model) 

解码器有几个问题。首先,为了匹配你的JSON,你将需要一个记录类型别名,它会公开一个单一的posts列表文章。

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

您缺少解码器的意见。这将是这样的:

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)) 
+0

此非常感谢,你帮助了很多! –

+0

你能看看这个问题吗?我再坚持这一点,进一步对结果我希望http://stackoverflow.com/questions/35845299/structure-mismatch-while-parsing-json –

+8

榆树新人:小心,这个答案包含pre- 0.18语法。特别是,':='已经变成'field','objectX'变成'mapX'。请参见[在核心中升级到0.18 /重新命名的函数](https://github.com/elm-lang/elm-platform/blob/master/upgrade-docs/0.18.md#renamed-functions-in-core) –