This is idential to this question, except elm has changed since then so that answer is no longer valid (in particular there is no longer a Decode.customDecoder
object).
How do you do this same thing in elm-core > 5.0.0?
One way to do it (as of Elm 0.18 and core 5.0) would be like this:
stringIntDecoder : Decoder Int
stringIntDecoder =
Json.Decode.map (\str -> String.toInt (str) |> Result.withDefault 0) Json.Decode.string
The String.toInt
function from the standard library takes a string and attempts to convert it to an integer, returning a Result. Result.withDefault
does what its name implies -- you give it some default value and a result, and if the Result is Ok x
you get x
but if it's Err _
you get the default value you supplied, here 0. You could instead write a function to handle a Result yourself if you like and pass that function in instead.
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