【发布时间】:2019-07-28 21:09:32
【问题描述】:
我明白了
我认为第一个与 elm 0.19 无关。我在NoRedInk/elm-json-decode-pipeline 中找不到decode 函数,我不相信:= 中缀运算符仍然有效。
第二个解决了基于 JSON 字段的值的条件解码略有不同的问题。
如果我有来自端口和以下类型的数据:
import Json.Decode 暴露(Decoder,map,oneOf,string,succeed,andThen,map2,map4)
import Json.Decode exposing (Decoder, andThen, map, map2, map4, oneOf, string, succeed, field)
port loginResponse : (Value -> msg) -> Sub msg
type Status
= Authenticated Data
| Unauthenticated (Maybe Error)
type alias Data =
{ accessToken : String
, email : String
, name : String
, nickname : String
}
dataDecoder : Decoder Data
dataDecoder =
map4 Data
(field "accessToken" string)
(field "email" string)
(field "name" string)
(field "nickname" string)
type alias Error =
{ error : String
, errorDescription : String
}
errorDecoder : Decoder Error
errorDecoder =
map2 Error
(field "error" string)
(field "errorDescription" string)
如何为标记联合类型Status 编写解码器来解码从端口返回的数据?
到目前为止我得到的最好的东西是这样的
statusDecoder : Decoder Status
statusDecoder =
oneOf
[ dataDecoder andThen (\data -> succeed (Authenticated data)
, errorDecoder andThen (\error -> succeed (Unauthenticated (Just error)))
]
这是无效的,或者
getStatus : Json.Decode.Value -> Status
getStatus value =
let
decodedData =
decodeValue dataDecoder value
in
case decodedData of
Ok data ->
Authenticated data
Err _ ->
let
decodedError =
decodeValue errorDecoder value
in
case decodedError of
Ok error ->
Unauthenticated (Just error)
Err err ->
Unauthenticated (Just { error = "There was a problem decoding the JSON", errorDescription = "" })
真的很丑,感觉不对。
【问题讨论】:
标签: json functional-programming elm decoder