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)