简体   繁体   English

Elm:使用 elm-decode-pipeline 解码嵌套的对象数组

[英]Elm: Decoding a nested array of objects with elm-decode-pipeline

I am struggling to convert a JSON response from OpenWeatherMap using NoRedInk/elm-decode-pipeline.我正在努力使用 NoRedInk/elm-decode-pipeline 转换来自 OpenWeatherMap 的 JSON 响应。 I have managed to decode nested objects within the JSON, but I cannot do the same for an array of objects我已经设法解码 JSON 中的嵌套对象,但我不能对对象数组做同样的事情

I've included the code I currently have.我已经包含了我目前拥有的代码。 It compiles but in fails when run with FetchWeather Err BadPayload ...它编译但在使用FetchWeather Err BadPayload ...

JSON JSON

{
     "weather":[{"id":804}],
     "main":{"temp":289.5},
}

CODE代码

type alias OpenWeatherResponse =
  { main: MainResult
  , weather: WeatherResult
  }

type alias MainResult =
  { temp: Float }

type alias ConditionResult =
  { code: Int }

decodeOpenWeatherResponse : Decoder OpenWeatherResponse
decodeOpenWeatherResponse =
    decode OpenWeatherResponse
        |> required "main" decodeMain
        |> required "weather" decodeConditions

decodeMain : Decoder MainResult
decodeMain =
    decode MainResult
        |> required "temp" float

decodeConditions : Decoder ConditionResult
decodeConditions =
     decode ConditionResult
        |> required "id" int -- This is clearly wrong --

You can use Json.Decode.list : Decoder a -> Decoder (List a) to make a parser of a list from a parser of an item.您可以使用Json.Decode.list : Decoder a -> Decoder (List a)从项目的解析器中生成列表的解析器。

decodeConditions : Decoder (List ConditionResult)
decodeConditions =
    Json.Decode.list decodeCondition

decodeCondition : Decoder ConditionResult
decodeCondition =
    decode ConditionResult
        |> required "id" int

Or, you can make it look like a part of the pipeline:或者,您可以让它看起来像管道的一部分:

decodeConditions : Decoder (List ConditionResult)
decodeConditions=
    decode ConditionResult
        |> required "id" int
        |> Json.Decode.list

Also, the response type has to have a list:此外,响应类型必须有一个列表:

type alias OpenWeatherResponse =
  { main : MainResult
  , weather : List ConditionResult
  }

If you just want the first item of the weather array, you can use Json.Decode.index : Int -> Decoder a -> Decoder a :如果你只想要weather数组的第一项,你可以使用Json.Decode.index : Int -> Decoder a -> Decoder a

decodeConditions : Decoder ConditionResult
decodeConditions =
     decode ConditionResult
        |> required "id" int
        |> Json.Decode.index 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM