2017-05-04 57 views
-2

我試圖使用雅虎API加載一些股票,但不能做到這一點,請大家幫忙JSON SWIFT 3解析送單串雅虎API

func getJSon() { 
    stockCode = self.stockCodeTextfield.text! 
    urlString = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D" + stockCode + "%26f%3Dsl1d1t1c1ohgv%26e%3D.csv'%20and%20columns%3D'symbol%2Cprice%2Cdate%2Ctime%2Cchange%2Ccol1%2Chigh%2Clow%2Ccol2'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys" 

    let url = NSURL(string: urlString) 
    let data = NSData(contentsOf: url! as URL) 
    let values = try! JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as! NSDictionary 

直到這 點加載JSON來Xcode中,我想我需要訪問某些鍵我迷路

let maindata = values[0] 
let price = maindata["price"] 
print(price) 

{ 「查詢」:{ 「計數」:1, 「創造」:「2017-05-04T22:24:25Z 」, 「郎」: 「EN-US」, 「結果」:{ 「行」:{ 「符號」: 「TERP」, 「價格」: 「12.30」, 「日期」: 「2017年5月4日」 「時間」: 「下午4:00」, 「變」: 「 - 0.12」, 「COL1」: 「12.41」, 「高」: 「12.51」, 「低」: 「12.28」, 「col2上」: 「366182」 }}}}

回答

-1

你提的問題是非常不明確,含糊的,但如果你問怎樣才能到「結果」你的JSON的部分答案很簡單,你可以這樣做:

if let query = values["query"] as? [String : Any], let results = query["results"] as? [String : Any], let row = results["row"] as? [String : Any] { 
    //Now you're inside the "results" dictionary 
} 

如果您需要從「結果」中打印的「價格」,你可以這樣做:

if let query = values["query"] as? [String : Any], let results = query["results"] as? [String : Any], let row = results["row"] as? [String : Any] { 
    if let row = results["row"] as? [String : Any], let price = row["price"] as? String { 
     print(price) 
    } 
} 
+0

謝謝!! creeperspeak – Joseluis