I'm looking to decode floats in JSON that are in quotes.
import Html exposing (text)
import Json.Decode as Decode
type alias MonthlyUptime = {
percentage: Maybe Float
}
decodeMonthlyUptime =
Decode.map MonthlyUptime
(Decode.field "percentage" (Decode.maybe Decode.float))
json = "{ \"percentage\": \"100.0\" }"
decoded = Decode.decodeString decodeMonthlyUptime json
main = text (toString decoded)
(Execute here)
This outputs Ok { percentage = Nothing }
.
I've been fairly confused by the documentation surrounding custom decoders, and it looks like some of it is out of date (for instance, references to Decode.customDecoder
)
Elm 0.19.1
Decode.field "percentage" Decode.string
|> Decode.map (String.toFloat >> MonthlyUptime)
Original answer
Instead of the andThen
I would suggest using a map
:
Decode.field "percentage"
(Decode.map
(String.toFloat >> Result.toMaybe >> MonthlyUptime)
Decode.string)
Looks like I figured it out with help from this question
import Html exposing (text)
import Json.Decode as Decode
json = "{ \"percentage\": \"100.0\" }"
type alias MonthlyUptime = {
percentage: Maybe Float
}
decodeMonthlyUptime =
Decode.map MonthlyUptime
(Decode.field "percentage" (Decode.maybe stringFloatDecoder))
stringFloatDecoder : Decode.Decoder Float
stringFloatDecoder =
(Decode.string)
|> Decode.andThen (\val ->
case String.toFloat val of
Ok f -> Decode.succeed f
Err e -> Decode.fail e)
decoded = Decode.decodeString decodeMonthlyUptime json
main = text (toString decoded)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With