ELM 如何解码 json 数组中的不同值

ELM how to decode different value in json array

我有一个 JSON 数组,数组中的值不同,但我不知道如何解析它。这是一个例子:

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

所以我的JSON是这样的,数组第一个元素是用户,第二个是公司。 我在 Elm 中有等效项:

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

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)