How to convert from String to Int in Json.Decoder

左心房为你撑大大i 提交于 2019-12-05 05:33:55

... and to answer myself :) I found the solution in this Flickr example

decodeData : Json.Decoder (Id, String)
decodeData =
  let number =
    Json.oneOf [ Json.int, Json.customDecoder Json.string String.toInt ]
  in
    Json.at ["data", "0"]
      <| Json.object2 (,)
        ("id" := number)
        ("label" := Json.string)

In Elm-0.18

Use parseInt decoder (source):

decodeString parseInt """ "123" """

Here is tutorial about custom decoders, like for date. Reuse fromResult approach.

The validated answer is obsolete. Here is an answer for Elm 0.19:

dataDecoder : Decoder Data
dataDecoder =
    Decode.map2 Data
        (Decode.field "id" (Decode.string |> Decode.andThen stringToIntDecoder))
        (Decode.field "label" Decode.string)


stringToIntDecoder : String -> Decoder Int
stringToIntDecoder year =
    case String.toInt year of
        Just value ->
            Decode.succeed value

        Nothing ->
            Decode.fail "Invalid integer"

And an executable example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!