7

Here's my decoder:

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

The id should logically be Int however my backend sends it as String (e.g. we get "1" instead of 1).

How can I cast the decoded value to Int?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
amitaibu
  • 1,026
  • 1
  • 7
  • 23

3 Answers3

7

... 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)
amitaibu
  • 1,026
  • 1
  • 7
  • 23
0

In Elm-0.18

Use parseInt decoder (source):

decodeString parseInt """ "123" """

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

rofrol
  • 14,438
  • 7
  • 79
  • 77
0

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

Pascal Le Merrer
  • 5,883
  • 20
  • 35