2016-12-20 28 views
2

我將通過端口的對象數組傳遞給我的Elm應用程序。數組中的對象的一個​​的一個例子是:通過Elm端口將對象導入JSON解碼器

{ 
    FullName: 'Foo Bar', 
    Location: 'Here' 
} 

正如你所看到的物體的按鍵用大寫字母開頭,所以我需要在榆樹解碼這些。在我的榆樹的代碼我對Person

type alias Person = 
    { fullName : String 
    , location : String 
    } 

和端口type

port getPeople : (List Json.Decode.Value -> msg) -> Sub msg 

最後我有一個解碼器(我使用Elm Decode Pipeline)將數據解析到Person類型。

peopleDecoder : Decoder Person 
peopleDecoder = 
    decode Person 
     |> required "FullName" string 
     |> required "Location" string 

我的問題是我怎麼輸入端口的數據映射到Person類型?我知道我可以在JS中這樣做,但我寧願在我的Elm代碼中執行此操作。

+0

在您的示例'peopleDecoder'中,什麼是'Workerer'? –

+0

這是一個錯字,現在修復。 – joshuahornby10

回答

4

Json.Decode.decodeValue可以解碼Json.Decode.Value,但它返回一個Result String (List Person)

如果你定義你的消息是這樣的:

type Msg 
    = GetPeople (Result String (List Person)) 

你可以設置你的訂閱像這樣:

port getPeople : (Json.Decode.Value -> msg) -> Sub msg 

subscriptions : Model -> Sub Msg 
subscriptions model = 
    getPeople (GetPeople << decodeValue (list peopleDecoder)) 

(注意,在該端口的第一個參數已更改爲只是一個Value而不是List Value