首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Elm:用elm解码管道解码嵌套的对象数组。

Elm:用elm解码管道解码嵌套的对象数组。
EN

Stack Overflow用户
提问于 2017-10-28 19:53:49
回答 1查看 1.2K关注 0票数 4

我很难用NoRedInk/elm-decode管道从OpenWeatherMap转换JSON响应。我已经成功地解码了JSON中嵌套的对象,但是我不能对对象数组进行同样的解码

我已经包括了我目前的代码。它编译,但在使用FetchWeather Err BadPayload ...运行时失败。

JSON

代码语言:javascript
复制
{
     "weather":[{"id":804}],
     "main":{"temp":289.5},
}

代码语言:javascript
复制
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 --
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-28 20:21:01

您可以使用Json.Decode.list : Decoder a -> Decoder (List a)从项的解析器中生成列表的解析器。

代码语言:javascript
复制
decodeConditions : Decoder (List ConditionResult)
decodeConditions =
    Json.Decode.list decodeCondition

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

或者,你可以让它看起来像管道的一部分:

代码语言:javascript
复制
decodeConditions : Decoder (List ConditionResult)
decodeConditions=
    decode ConditionResult
        |> required "id" int
        |> Json.Decode.list

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

代码语言:javascript
复制
type alias OpenWeatherResponse =
  { main : MainResult
  , weather : List ConditionResult
  }

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

代码语言:javascript
复制
decodeConditions : Decoder ConditionResult
decodeConditions =
     decode ConditionResult
        |> required "id" int
        |> Json.Decode.index 0
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46993855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档