【问题标题】:ELM how to decode different value in json arrayELM如何解码json数组中的不同值
【发布时间】:2017-01-25 05:43:08
【问题描述】:

我有一个 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

【问题讨论】:

    标签: arrays json parsing decode elm


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 2020-05-02
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多