我已经定义了一个简单的serverResponse
来模拟从api到elm-lang解析的响应。
我遇到问题从Result
转到显示信息的HTML!
最好的方法是什么?
import String exposing (..)
import String exposing (..)
import List exposing (..)
import Result exposing (map)
import Json.Decode as Json exposing (..)
type alias Team =
{ department : String
, names: List String
}
serverResponse =
"""
[{"department":"product","names":["bob","sally","george"]},{"department":"marketing","names":["billy","diane","anita"]},{"department":"sales","names":["howard","steve","isha"]}]
"""
stringDecoder =
Json.list Json.string
infoDecoder : Json.Decoder Team
infoDecoder =
Json.map2 Team
(Json.field "department" Json.string)
(Json.field "names" stringDecoder)
teamDecoder : Json.Decoder (List Team)
teamDecoder =
Json.list infoDecoder
toList team =
p [] [
team.department
]
transformList teams =
toList teams
main =
Json.decodeString teamDecoder serverResponse
|> toString
|> text
答案 0 :(得分:2)
您可以使用case
语句提取解码结果。这允许您明确地处理解码器的成功和失败。
您的main
功能可以更改为以下内容(请注意,我已重新定义toList
,因为您没有返回有效的Html):
toList : Team -> Html msg
toList team =
p [] [ text team.department ]
main =
case Json.decodeString teamDecoder serverResponse of
Ok teams ->
div [] (List.map toList teams)
Err msg ->
text ("ERROR: " ++ msg)
Result
是一个带有两个构造函数的联合类型:Ok
和Err
。您可以阅读union types in the Elm Guide。
答案 1 :(得分:0)
还有withDefault
用于快速检查
Result.withDefault 0 (String.toInt "123") == 123