rogger2016 rogger2016 - 3 months ago 18
Swift Question

loop over json in SwiftyJSON

I am receiving some JSON from an end point, but I'm having issues when I try and loop through the data and pass to a SwiftyJSON object

the json :

{
findItemsByKeywordsResponse:[
{
searchResult:[
{
item:[
{
itemId:[
"232053825102"
]
},
{
itemId:[
"232053825102"
]
}
}
]
}
]
}


Im trying to loop through the itemId's

Some sauce:

if let data = response.data {
if let jsonData:JSON? = JSON(data: data){
if let findItems = jsonData["findItemsByKeywordsResponse"].array {//This line works
if let searchResult //HERES THE ERROR, HOW TO LOOP findItems?????
}
}
}


Any help greatly appreciated

Regards

Answer

This is the code to access each itemId string

guard let data = response.data else { return }
let json = JSON(data:data)
guard let jsonElms = json["findItemsByKeywordsResponse"].array?.first?["searchResult"].array?.first?["item"].array else { return }

for elm in jsonElms {
    let itemID = elm["itemId"].array?.first?.string
}