Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from String to Int in Json.Decoder in elm-core > 5.0.0

Tags:

json

elm

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?

like image 382
vitiral Avatar asked Dec 15 '22 02:12

vitiral


1 Answers

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.

like image 85
Ryan Plant Avatar answered Dec 17 '22 01:12

Ryan Plant