Elm:将以字符串编码的浮点数解码为JSON

5

我想要解码被引号包裹的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)

(在此处执行

这将输出Ok { percentage = Nothing }

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

2个回答

4
Elm 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)

2

看起来我在这个问题的帮助下解决了它。

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接