2016-11-15 55 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)