访问权如何对列表中的对象进行多次转换

时间:2017-07-31 17:45:47

标签: elm

我在Elm-lang中有这个代码:

import Json.Decode exposing (..)
import Html exposing (..)


json =  -- List that contains and will have many users
 """
 [{\"ssn\":\"111.111.111-11\",\"name\":\"People Silva\",\"email\":\"people@eat.com\"}, {\"ssn\":\"000.000.000-00\",\"name\":\"Pet Silva\",\"email\":\"pet@eat.com\"}]
 """

type alias User =
  { name : String
  , email: String
  , ssn: String
  }


userDecoder : Json.Decode.Decoder User
userDecoder =
  Json.Decode.map3 User
    (field "name" string)
    (field "email" string)
    (field "ssn" string)


userListDecoder : Json.Decode.Decoder (List User)
userListDecoder =
  Json.Decode.list userDecoder


main =
  let
    decoded = (decodeString userListDecoder json)
  in
    case decoded of
      Ok u ->
        span [] [text (toString u)]

      Err e ->
        span [] [text (toString e)]

这段代码工作得非常好,并输出了这个(预期的方式):

[{ name = "People Silva", email = "people@eat.com", ssn = "111.111.111-11" },{ name = "Pet Silva", email = "pet@eat.com", ssn = "000.000.000-00" }]

这里开始我怀疑,如何获取列表中所有用户的列表?(并且还作为奖励,获取列表中的用户数量)

-- already tried, unsuccessfully
u[0].name
u[1].name

1 个答案:

答案 0 :(得分:1)

用户的值为List User,因此您可以使用functions from the List package来访问它们。

如果您想从用户列表中获取用户名列表,可以拨打List.map .name users

如果要在自己的div中编写用户名,可以这样写:

showUser : User -> Html msg
showUser user =
    div [] [ text user.name ]

并从main这样调用它:

main =
  let
    decoded = (decodeString userListDecoder json)
  in
    case decoded of
      Ok users ->
        div [] (List.map showUser users)

      Err e ->
        span [] [text (toString e)]

获取列表的长度只需使用List.length函数:List.length users