Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm: decoding floats encoded as strings in JSON

I'm looking to decode floats in JSON that are in quotes.

import Html exposing (text)    
import Json.Decode as Decode

type alias MonthlyUptime = {
  percentage: Maybe Float
}

decodeMonthlyUptime =
  Decode.map MonthlyUptime
    (Decode.field "percentage" (Decode.maybe Decode.float))        

json = "{ \"percentage\": \"100.0\" }"   
decoded = Decode.decodeString decodeMonthlyUptime json  

main = text (toString decoded)

(Execute here)

This outputs Ok { percentage = Nothing }.

I've been fairly confused by the documentation surrounding custom decoders, and it looks like some of it is out of date (for instance, references to Decode.customDecoder)

like image 593
tanman Avatar asked Nov 15 '16 23:11

tanman


2 Answers

Elm 0.19.1

Decode.field "percentage" Decode.string
    |> Decode.map (String.toFloat >> MonthlyUptime)


Original answer

Instead of the andThen I would suggest using a map:

Decode.field "percentage" 
    (Decode.map 
       (String.toFloat >> Result.toMaybe >> MonthlyUptime)
       Decode.string)
like image 165
Simon H Avatar answered Oct 12 '22 14:10

Simon H


Looks like I figured it out with help from this question

import Html exposing (text)

import Json.Decode as Decode

json = "{ \"percentage\": \"100.0\" }"

type alias MonthlyUptime = {
  percentage: Maybe Float
}

decodeMonthlyUptime =
  Decode.map MonthlyUptime
    (Decode.field "percentage" (Decode.maybe stringFloatDecoder))

stringFloatDecoder : Decode.Decoder Float
stringFloatDecoder =
  (Decode.string)
  |> Decode.andThen (\val ->
    case String.toFloat val of
      Ok f -> Decode.succeed f
      Err e -> Decode.fail e)

decoded = Decode.decodeString decodeMonthlyUptime json


main = text (toString decoded)
like image 33
tanman Avatar answered Oct 12 '22 14:10

tanman