尤川豪   ·  1年前
445 貼文  ·  275 留言

Elm json decoder 是否有設計失敗的問題?

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

這樣才一致

在這邊的設計,是否有問題呢?

  分享   共 494 次點閱
共有 1 則留言
尤川豪   ·  1年前
445 貼文  ·  275 留言
 
您的留言
尤川豪
445 貼文  ·  275 留言

Devs.tw 是讓工程師寫筆記、網誌的平台。隨手紀錄、寫作,方便日後搜尋!

歡迎您一起加入寫作與分享的行列!

查看所有文章