Ameya Vichare Ameya Vichare - 4 months ago 34
Swift Question

SwiftyJson: Looping an array inside an array

I am trying to loop through an array inside an array. The first loop was easy but I'm having trouble looping through the second array inside it. Any suggestions would be welcome!

{
"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
}
]
}
]
}


As you see I'm having trouble to reach through to the message field etc

Here's my code on swiftyjson

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"])

}


The output I get is

4
andre gomes
I am user 4
0
0
5
renato sanchez
I am user 5
0
0


As you see I'm unable to get the message"I am user 5-2" and corresponding like_count and comment_count

Answer

You already demonstrated how to loop through a JSON array so you only need to do it again with the inner feeds:

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"])
    }

}

If you only want the first item in the inner feeds array, replace the inner for lop with this:

print(item["feeds"].arrayValue[0]["message"])
print(item["feeds"].arrayValue[0]["like_count"])
print(item["feeds"].arrayValue[0]["comment_count"])
Comments