2017-07-26 28 views
1

試圖解碼更大的json值時,我遇到了Json-Decode-Extra庫中的以下代碼。 (位於hereElm Colon Equals Operator

import Date (Date) 

type alias User = 
    { id    : Int 
    , createdAt   : Date 
    , updatedAt   : Date 
    , deletedAt   : Maybe Date 
    , username   : Maybe String 
    , email    : Maybe String 
    , fullname   : Maybe String 
    , avatar   : Maybe String 
    , isModerator  : Bool 
    , isOrganization : Bool 
    , isAdmin   : Bool 
    } 

metaDecoder : (Int -> Date -> Date -> Maybe Date -> b) -> Decoder b 
metaDecoder f = f 
    `map`  ("id"  := int) 
    `apply` ("createdAt" := date) 
    `apply` ("updatedAt" := date) 
    `apply` ("deletedAt" := maybe date) 

userDecoder : Decoder User 
userDecoder = metaDecoder User 
    `apply` ("username"   := maybe string) 
    `apply` ("email"    := maybe string) 
    `apply` ("fullname"   := maybe string) 
    `apply` ("avatar"   := maybe string) 
    `apply` ("isModerator"  := bool) 
    `apply` ("isOrganization" := bool) 
    `apply` ("isAdmin"   := bool) 

不過,我經常跑到了:=操作編譯錯誤。這個定義在哪裏? JSON解碼教程不會在任何地方顯式導入此運算符。

回答

5

在Elm 0.18中,:=運算符被Json.Decode.field替換,並且使用反引號操作符的反引號被刪除。

您正在使用尚未更新至Elm 0.18的包(circuithub/elm-json-extra)。

考慮切換到使用由Elm社區維護的包:elm-community/json-extra。您可以使用andMap而不是apply。下面是升級到新圖書館和榆樹0.18您的示例代碼:

import Date exposing (Date) 
import Json.Decode exposing (..) 
import Json.Decode.Extra exposing (andMap, date) 

metaDecoder : (Int -> Date -> Date -> Maybe Date -> b) -> Decoder b 
metaDecoder f = 
    succeed f 
     |> andMap (field "id" int) 
     |> andMap (field "createdAt" date) 
     |> andMap (field "updatedAt" date) 
     |> andMap (field "deletedAt" (maybe date)) 

userDecoder : Decoder User 
userDecoder = 
    metaDecoder User 
     |> andMap (field "username" (maybe string)) 
     |> andMap (field "email" (maybe string)) 
     |> andMap (field "fullname" (maybe string)) 
     |> andMap (field "avatar" (maybe string)) 
     |> andMap (field "isModerator" bool) 
     |> andMap (field "isOrganization" bool) 
     |> andMap (field "isAdmin" bool) 

注意,elm-community/json-extra包還出口中綴運算符|:這是andMap中綴版本。你可以用它來使你的代碼更加簡潔。例如:

metaDecoder : (Int -> Date -> Date -> Maybe Date -> b) -> Decoder b 
metaDecoder f = 
    succeed f 
     |: field "id" int 
     |: field "createdAt" date 
     |: field "updatedAt" date 
     |: field "deletedAt" (maybe date)