我正在尝试解析JSON文件并将其显示给用户,这是一个简化版本
{
"posts": [{
// some properties
comments: {
// some more properties
}
}
这是我的代码,我知道很多我并不确定要删除什么来隔离问题,每次我尝试时都会遇到一个似乎无处可寻的错误。
type Action
= NoOp
| GetPosts
| ShowPosts (Maybe { posts : List Post.Model })
init =
( { posts = Nothing }, Effects.none )
update action model =
case action of
NoOp ->
( model, Effects.none )
GetPosts ->
( { model | posts = Nothing }, getPosts )
ShowPosts maybePosts ->
( { model | posts = maybePosts }, Effects.none )
view address model =
div
[]
[ button [ onClick address GetPosts ] [ text "Click to get posts!" ]
, viewPosts model.posts
]
viewPosts maybePosts =
case maybePosts of
Nothing ->
div [] [ text "No posts to display. Try clicking the button" ]
Just posts ->
ul [] (List.map Post.view posts)
-- This is the key to map the result of the HTTP GET to an Action
-- Note: Task.toMaybe swallows any HTTP or JSON decoding errors
getPosts : Effects Action
getPosts =
Http.get decoderColl "./posts.json"
|> Task.toMaybe
|> Task.map ShowPosts
|> Effects.task
type alias PostListContainerModel =
{ posts : List Post.Model }
postDecoder : Decoder Post.Model
postDecoder =
Decode.object5
Post.Model
("img" := Decode.string)
("text" := Decode.string)
("source" := Decode.string)
("date" := Decode.string)
("comments" := Decode.list commentDecoder)
commentDecoder : Decoder Comment.Model
commentDecoder =
Decode.object2
Comment.Model
("text" := Decode.string)
("date" := Decode.string)
decoderColl : Decoder PostListContainerModel
decoderColl =
Decode.object1
PostListContainerModel
("posts" := Decode.list postDecoder)
我从编译器中收到此错误
函数
start
期望参数为:{ ... , view : Signal.Address Action -> { posts : Maybe { posts : List Post.Model } } -> Html }
但它是:
{ ... , view : Signal.Address Action -> { posts : Maybe (List Post.Model) } -> Html }
我无法理解{ posts : Maybe
定义中额外view
的来源。
上一个问题有一些额外的背景:Parsing nested JSON in Elm
更新:
在elm社区google小组中找到了答案,这里的要点是https://gist.github.com/rundis/23d7ef6ea42842e6f527
答案 0 :(得分:1)
我认为ShowPosts
的定义正在阻碍。你有这个:
ShowPosts (Maybe { posts : List Post.Model })
但它应该是这样的:
ShowPosts (Maybe (List Post.Model))
进行此更改将导致您必须更新其他一些地方,但请遵循编译器消息,它应该引导您到达正确的位置。
需要更新的地方之一是getPosts
,您需要从该包装对象中获取帖子列表。这应该就是这么简单:
|> Task.map (ShowPosts << .posts)