2016-11-15 54 views
3

我正在寻找解码在引号中的JSON中的浮点数。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引用)

回答

1

看起来像我的帮助了它从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) 
2

取而代之的是andThen的我会建议使用map

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