我需要消费一个JSON数据源,其中数字类型的float
表示为string
类型,但我不知道该如何操作。
这个问题几乎可以轻松解决:
Json.Decode.map String.toFloat Json.Decode.string
然而,这会产生一个Maybe Float
,如果无法解码字符串,我更希望它完全失败。
(*) 这样做的原因是真实的数据类型是 Decimal,所以 "1.5" != "1.50"。不过我的应用程序并不在意这一点。
我需要消费一个JSON数据源,其中数字类型的float
表示为string
类型,但我不知道该如何操作。
这个问题几乎可以轻松解决:
Json.Decode.map String.toFloat Json.Decode.string
然而,这会产生一个Maybe Float
,如果无法解码字符串,我更希望它完全失败。
(*) 这样做的原因是真实的数据类型是 Decimal,所以 "1.5" != "1.50"。不过我的应用程序并不在意这一点。
elm-community/json-extra
并使用 Json.Decode.Extra.parseFloat
,或者直接复制其实现。fromMaybe : String -> Maybe a -> Decode.Decoder a
fromMaybe error val =
case val of
Just v ->
Decode.succeed v
Nothing ->
Decode.fail error
parseFloat : Decode.Decoder Float
parseFloat =
Decode.string |> Decode.andThen (String.toFloat >> fromMaybe "failed to parse as float")
fromMaybe
不必要的选项:floatDecoder : Json.Decoder Float
floatDecoder =
Json.string |> Json.andThen (String.toFloat >> Maybe.withDefault 0.0 >> Json.succeed)