2016-03-04 115 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) –