Elm:解码在JSON中编码为字符串的浮点数

时间:2016-11-15 23:00:59

标签: json functional-programming elm

我正在寻找JSON中带引号的浮点数。

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)

(执行here

这会输出Ok { percentage = Nothing }

我对自定义解码器周围的文档感到相当困惑,看起来其中一些已过时(例如,对Decode.customDecoder的引用)

2 个答案:

答案 0 :(得分:3)

而不是andThen我会建议使用map

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

答案 1 :(得分:2)

看起来我在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)