Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from String to Int in Json.Decoder

Tags:

json

elm

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?

like image 443
amitaibu Avatar asked Sep 07 '15 18:09

amitaibu


1 Answers

... 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)
like image 177
amitaibu Avatar answered Nov 18 '22 21:11

amitaibu