首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SwiftyJson:在数组中循环数组

SwiftyJson:在数组中循环数组
EN

Stack Overflow用户
提问于 2016-07-30 15:09:30
回答 1查看 735关注 0票数 3

我正在尝试遍历数组中的数组。第一个循环很简单,但是我在循环第二个数组时遇到了麻烦。欢迎任何建议!

代码语言:javascript
复制
{
"feeds": [
{
  "id": 4,
  "username": "andre gomes",
  "feeds": [
    {
      "message": "I am user 4",
      "like_count": 0,
      "comment_count": 0
    }
  ]
},
{
  "id": 5,
  "username": "renato sanchez",
  "feeds": [
    {
      "message": "I am user 5",
      "like_count": 0,
      "comment_count": 0
    },
    {
      "message": "I am user 5-2",
      "like_count": 0,
      "comment_count": 0
    }
  ]
}
]
}

如您所见,我很难到达消息字段等。

这是我对金丝提斯的密码

代码语言:javascript
复制
let json = JSON(data: data!)

for item in json["feeds"].arrayValue {

print(item["id"].stringValue)
print(item["username"].stringValue)
print(item["feeds"][0]["message"])
print(item["feeds"][0]["like_count"])
print(item["feeds"][0]["comment_count"])

}

我得到的输出是

代码语言:javascript
复制
4
andre gomes
I am user 4
0
0
5
renato sanchez
I am user 5
0
0

如您所见,我无法得到消息“I是用户5-2”以及相应的like_count和comment_count。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-30 15:21:33

您已经演示了如何循环使用JSON数组,因此您只需要再次使用内部feeds进行循环。

代码语言:javascript
复制
let json = JSON(data: data!)

for item in json["feeds"].arrayValue {

    print(item["id"].stringValue)
    print(item["username"].stringValue)

    for innerItem in item["feeds"].arrayValue {
        print(innerItem["message"])
        print(innerItem["like_count"])
        print(innerItem["comment_count"])
    }

}

如果只想要内部feeds数组中的第一项,请用以下内容替换内部for lop:

代码语言:javascript
复制
print(item["feeds"].arrayValue[0]["message"])
print(item["feeds"].arrayValue[0]["like_count"])
print(item["feeds"].arrayValue[0]["comment_count"])
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38675397

复制
相关文章

相似问题

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