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

时间:2017-10-28 19:53:49

标签: json decode elm

我正在努力使用NoRedInk / elm-decode-pipeline从OpenWeatherMap转换JSON响应。我已设法解码JSON中的嵌套对象,但我不能对对象数组执行相同的操作

我已经包含了我目前拥有的代码。它编译但在使用FetchWeather Err BadPayload ...

运行时失败

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 --

1 个答案:

答案 0 :(得分:5)

您可以使用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

或者,您可以将其看作管道的一部分:

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

此外,响应类型必须有一个列表:

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

修改

如果您只想要weather数组的第一项,可以使用Json.Decode.index : Int -> Decoder a -> Decoder a

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