2016-09-16 79 views
3

我在数组中有一个JSON数组,其值不同,我不知道如何解析它。这里是一个例子:ELM如何解码json数组中的不同值

[ 
    { 
    "firstname": "John", 
    "lastname": "Doe", 
    "age": 30 
    }, 
    { 
    "companyName": "Doe enterprise", 
    "location": "NYC", 
    "numberOfEmployee": 10 
    } 
] 

所以我的JSON是这样的,数组的第一个元素是一个用户,第二个公司。 我在榆树等价的:

type alias User = 
    { firsname : String 
    , lastname : String 
    , age : Int 
    } 

type alias Company = 
    { companyName : String 
    , location : String 
    , numberOfEmployee : Int 
    } 

则:Task.perform FetchFail FetchPass (Http.get decodeData url)

那么如何让我的UserCompany通过我的FetchPass函数? 有一些像Json.Decode.at但它仅用于对象。 在这里有一种方法来做这样的事情?

decodeData = 
    Json.at [0] userDecoder 
    Json.at [1] companyDecoder 

回答

5

Json.at也适用于数组索引。首先,您需要一个Data类型来保存用户和公司:

import Json.Decode as Json exposing ((:=)) 

type alias Data = 
    { user : User 
    , company : Company 
    } 

你还需要为用户和公司简单的解码器:

userDecoder : Json.Decoder User 
userDecoder = 
    Json.object3 User 
    ("firstname" := Json.string) 
    ("lastname" := Json.string) 
    ("age" := Json.int) 

companyDecoder : Json.Decoder Company 
companyDecoder = 
    Json.object3 Company 
    ("companyName" := Json.string) 
    ("location" := Json.string) 
    ("numberOfEmployee" := Json.int) 

最后,你可以使用Json.at得到这些数组索引处的值。与你的例子不同的是,你需要传递一个包含整数索引而不是int的字符串:

dataDecoder : Json.Decoder Data 
dataDecoder = 
    Json.object2 Data 
    (Json.at ["0"] userDecoder) 
    (Json.at ["1"] companyDecoder)