2015-09-14 16 views
17

Tôi có dữ liệu này sử dụng http://jsonapi.org/ định dạng:Elm: Làm thế nào để giải mã dữ liệu từ JSON API

{ 
    "data": [ 
     { 
      "type": "prospect", 
      "id": "1", 
      "attributes": { 
       "provider_user_id": "1", 
       "provider": "facebook", 
       "name": "Julia", 
       "invitation_id": 25 
      } 
     }, 
     { 
      "type": "prospect", 
      "id": "2", 
      "attributes": { 
       "provider_user_id": "2", 
       "provider": "facebook", 
       "name": "Sam", 
       "invitation_id": 23 
      } 
     } 
    ] 
} 

tôi có các mô hình của tôi như:

type alias Model = { 
    id: Int, 
    invitation: Int, 
    name: String, 
    provider: String, 
    provider_user_id: Int 
} 

type alias Collection = List Model 

Tôi muốn giải mã json vào một Bộ sưu tập, nhưng không biết làm thế nào.

fetchAll: Effects Actions.Action 
fetchAll = 
    Http.get decoder (Http.url prospectsUrl []) 
    |> Task.toResult 
    |> Task.map Actions.FetchSuccess 
    |> Effects.task 

decoder: Json.Decode.Decoder Collection 
decoder = 
    ? 

Làm cách nào để triển khai bộ giải mã? Cảm ơn

Trả lời

22

N.B. Json.Decode docs

Hãy thử điều này:

import Json.Decode as Decode exposing (Decoder) 
import String 

-- <SNIP> 

stringToInt : Decoder String -> Decoder Int 
stringToInt d = 
    Decode.customDecoder d String.toInt 

decoder : Decoder Model 
decoder = 
    Decode.map5 Model 
    (Decode.field "id" Decode.string |> stringToInt) 
    (Decode.at ["attributes", "invitation_id"] Decode.int) 
    (Decode.at ["attributes", "name"] Decode.string) 
    (Decode.at ["attributes", "provider"] Decode.string) 
    (Decode.at ["attributes", "provider_user_id"] Decode.string |> stringToInt) 

decoderColl : Decoder Collection 
decoderColl = 
    Decode.map identity 
    (Decode.field "data" (Decode.list decoder)) 

Phần khôn lanh được sử dụng để biến stringToInt lĩnh vực chuỗi thành số nguyên. Tôi đã làm theo các ví dụ API về int là gì và chuỗi là gì. Chúng tôi may mắn một chút rằng String.toInt trả lại một Result như mong đợi bởi customDecoder nhưng có đủ tính linh hoạt để bạn có thể tinh vi hơn một chút và chấp nhận cả hai. Thông thường bạn sẽ sử dụng map cho loại điều này; customDecoder về cơ bản là map cho các chức năng có thể không thành công.

Bí quyết khác là sử dụng Decode.at để vào bên trong đối tượng con attributes.

+0

Tôi có thể hữu ích nếu bạn cũng giải thích cách ánh xạ giá trị vào Kết quả. –

+0

OP chỉ được hỏi về việc triển khai Bộ giải mã. Để có được kết quả, hãy gọi 'Json.Decode.decodeString' hoặc' decodeValue'. – mgold

+2

Decode.object5 bây giờ là Decode.map5 – madnight

Các vấn đề liên quan