我有以下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
}
如何使用Swift 3访问(“解析”)值(2459.27,2447.83,2443.25,...)?
答案 0 :(得分:1)
请试试这个:
let aData = yourResponse["data"]
print(aData)
for aValue in aData!{
print(aValue["value"])
}
希望它会对你有所帮助。
答案 1 :(得分:1)
您可以尝试以下代码:
// 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 Types,Optional Binding。
答案 2 :(得分: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)