2015-11-05 64 views
0

循環我有一個JSON文件,這樣循環內的迅速

"vars": [ 
        { 
        "key": "f1", 
        "link": "@cooldownchampion", 
        "coeff": [ 
         24, 
         23, 
         22, 
         21, 
         20 
        ] 
        }, 
        { 
        "key": "f4", 
        "link": "@text", 
        "coeff": [ 
         150, 
         175, 
         200, 
         225, 
         250, 
         275, 
         300, 
         325, 
         350, 
         375, 
         400, 
         425, 
         450, 
         475, 
         500, 
         525, 
         550, 
         575 
        ] 
        } 
       ] 

我想要做的內部循環迴路以獲取係數_

所有項的數組,這是我的循環

for (key,subJson):(String, JSON) in newjson["vars"]{ 
    for (key,subJson):(String, JSON) in newjson["vars"][key]["coeff"]{ 
     print (subJson) // this should print 24/23/22/21 but it doesn't 
} 

} 

如你所知,我使用SWIFTYJSON庫處理JSON FILE

+0

那麼它打印代替? –

+0

//這應該打印24/23/22/21,但它不,只是空 –

+0

當你的JSON密鑰關聯到一個數組時,你需要使用'array'屬性。同樣,你需要使用正確的屬性來獲得期望類型的可選項(ej'.int','.string'等)。 'newjson [「vars」]。array'例如。 –

回答

-1

我不知道如何用swift

如果使用對象的C

NSArray *vars = [jsonDict objectForKey:@"vars"]; 

for (NSDictionary *dict in vars) { 

    NSString *key = [dict objectForKey:@"key"]; 

    NSArray *coeff = [dict objectForKey:@"coeff"]; 

} 
+0

謝謝但實際上我無法啓動OBJECT-C ^^「和我不能將此代碼嵌入到我的swift代碼中:( –

0

的問題是,你的第一個keyString和指數需要一個Int訪問到的元素。

您可以通過鑄造解決這個問題:

for (key,subJson):(String, JSON) in newjson["vars"] { 
    for (key,subJson):(String, JSON) in newjson["vars"][Int(key)!]["coeff"]{ 
     print (subJson) // this should print 24/23/22/21 but it doesn't 
    } 
} 

但更好的方法是使用現有的JSON對象(subJson)是這樣的:

for (key,subJson):(String, JSON) in newjson["vars"] { 
    for (key,subJson):(String, JSON) in subJson["coeff"]{ 
     print (subJson) // this should print 24/23/22/21 but it doesn't 
    } 
} 
+0

@Alexandre Perez我沒有看到你的答案,對'重複' – user3441734

+0

感謝你的工作:) –

+0

@MohammedAwad你應該接受答案來標記這個問題爲解決!) – awph

0
for (key,subJson):(String, JSON) in newjson["vars"]{ 
    for (key,subJson):(String, JSON) in newjson["vars"][indexInTheArray]["coeff"]{ 
     print (subJson) // this should print 24/23/22/21 but it doesn't 
} 

} 

你索引與鍵:字符串的數組,indexInTheArray應該是一個整數