Devs.tw 是讓工程師寫筆記、網誌的平台。歡迎您隨手紀錄、寫作,方便日後搜尋!
https://tech.chefclub.tv/en/how-to-decode-complex-json-with-elm
type alias Record =
{ uid : String
, age : Maybe Int
, version : Float
}
customDecoder : JD.Decoder Record
customDecoder =
decode Record
|> required "uid" JD.string
|> optional "age" (JD.maybe JD.int) Nothing
|> hardcoded 1.0
Note that the only link we see between a Elm Record and a JSON object is the decoder parameter order. In our case there are no links between the version field in the JSON object and the version property of our record.
在這邊 decoder 沒有指定 version
欄位名稱 就給值 1.0
如果是這樣的話 那前面兩欄也不需要給名稱 因為認定「欄位順序有意義」
customDecoder : JD.Decoder Record
customDecoder =
decode Record
|> required JD.string
|> optional (JD.maybe JD.int) Nothing
|> hardcoded 1.0
這樣才一致
在大部份程式語言 record / object / dictionary 這種資料結構 欄位順序都是沒意義的
不然的話 應該要給欄位名稱
customDecoder : JD.Decoder Record
customDecoder =
decode Record
|> required "uid" JD.string
|> optional "age" (JD.maybe JD.int) Nothing
|> hardcoded "version" 1.0
這樣才一致
在這邊的設計,是否有問題呢?