2016-11-15 3 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) 
関連する問題