2017-07-22 245 views
-4

我有以下JSON數據:解析JSON數組中的JSON對象?

{ 
    "data":[ 
     {"date":"2017-07-14","value":2459.27}, 
     {"date":"2017-07-13","value":2447.83}, 
     {"date":"2017-07-12","value":2443.25}, 
     {"date":"2017-07-11","value":2425.53}, 
     {"date":"2017-07-10","value":2427.43}, 
     {"date":"2017-07-07","value":2425.18}, 
     {"date":"2017-07-06","value":2409.75}, 
     {"date":"2017-07-05","value":2432.54}, 
     {"date":"2017-07-03","value":2429.01} 
    ], 
    "identifier":"$SPX", 
    "item":"close_price", 
    "result_count":9, 
    "page_size":100, 
    "current_page":1, 
    "total_pages":1, 
    "api_call_credits":1 
} 

如何訪問( 「解析」)的值(2459.27,2447.83,2443.25,...)與斯威夫特3?

回答

0

你可以試試這個代碼:

// 1. Access yourJSON ["data"] only if you have ensured that the data type of yourJSON["data"] is correct as you have envisioned. 
if let dataArray = yourJSON["data"] as? [[String : Any]] { 

    // 2. Execute a loop (for-in) to access each element of the array. 
    for element in dataArray { 

     // 3. Make sure that the "value" key of each element is of Double (or Float) type. 
     if let value = element["value"] as? Double { 
      print(value) 
     } 
    } 
} 

這裏有一些文件,你可以參考到:Collection TypesOptional Binding

1

請試試這個:

let aData = yourResponse["data"] 
     print(aData) 

     for aValue in aData!{ 

      print(aValue["value"]) 
     } 

希望它會幫助你。

0

您可以使用這樣的事情..

var dataValues:[[String:AnyObject]] = [] 
var valuesArray = [String]() 
自己的函數中

然後

self.dataValues = result?["data"] as! [[String:AnyObject]] 
for fields in self.dataValues { 
    valuesArray.append(fields["value"] as! String) 
} 

print("Your value array ", valuesArray)