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

Elm: decoding floats encoded as strings in JSON

我想解码 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 的引用)

看来我在

的帮助下弄明白了
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)

榆木 0.19.1

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


原回答

我建议使用 map:

而不是 andThen
Decode.field "percentage" 
    (Decode.map 
       (String.toFloat >> Result.toMaybe >> MonthlyUptime)
       Decode.string)