Elm - 获取 JSON 列表数据

Elm - Get JSON List Data

我正在尝试从此 URL 获取 JSON 数据列表:https://raw.githubusercontent.com/raywenderlich/recipes/master/Recipes.json

在这种情况下我不知道该怎么办

...
main =
  App.program
  { init = init
  , view = view
  , update = update
  , subscriptions = \_ -> Sub.none
  }

-- MODEL

type alias Model =
  { name : String
  , imageURL: String
  }

init =
  (Model "" "", Cmd.none)

-- UPDATE

type Msg
  = Recipes
  | FetchSucceed (List Model)
  | FetchFail Http.Error

update msg model =
  case msg of
    Recipes ->
      (model, fetchRecipes)

    FetchSucceed recipe ->
      (recipe, Cmd.none)

    FetchFail _ ->
      (model, Cmd.none)


-- VIEW

view model =
  div []
    [ ul [] (List.map getItem model)
  ]


getItem item =
  li [] [ text item.name ]

-- HTTP

fetchRecipes =
  let
    url =
      "https://raw.githubusercontent.com/raywenderlich/recipes/master/Recipes.json"
  in
    Task.perform FetchFail FetchSucceed (Http.get decodeListRecipes url)


decodeRecipes =
  Json.object2 Model
    ("name" := Json.string)
    ("imageURL" := Json.string)

decodeListRecipes =
  Json.list decodeRecipes

但是我一直收到这个错误:

Function `program` is expecting the argument to be:
    { ...,
      update :
        Msg
          -> { imageURL : String, name : String }
          -> ( { imageURL : String, name : String }, Cmd Msg ) ,
        view : { imageURL : String, name : String } -> Html Msg
    }

But it is: 
   { ...
   , update : Msg -> List Model -> ( List Model, Cmd Msg )
   , view : List { a | name : String } -> Html b
   }

您的 FetchSucceed 标记被定义为具有模型列表 (FetchSucceed (List Model)),但在您的 update 函数中,您将其视为单个模型而不是一个列表。如果我将值改为复数,它应该强调问题区域:

FetchSucceed recipes ->
    (recipes, Cmd.none)

在不知道您想要实现什么的情况下,我只能提供一个潜在解决方案的提示,例如,如果您只想获取列表的第一个元素,如果没有则返回当前模型食谱被退回,你可以这样做:

FetchSucceed recipes ->
    let recipe =
        case List.head recipes of
            Just r -> r
            Nothing -> model
    in
        (recipe, Cmd.none)