-4

I have the following JSON data:

{
    "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
}

How can I access ("parse") the values (2459.27, 2447.83, 2443.25, ...) with Swift 3?

Anh Pham
  • 2,108
  • 9
  • 18
  • 29

3 Answers3

2

You can try this code:

// 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)
        }
    }
}

Here are some documents you can refer to: Collection Types, Optional Binding.

Anh Pham
  • 2,108
  • 9
  • 18
  • 29
1

Please try this:

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

        for aValue in aData!{

            print(aValue["value"])
        }

Hope it will help you.

Garima Saini
  • 173
  • 8
0

You can use something like this ..

var dataValues:[[String:AnyObject]] = []
var valuesArray = [String]()

Then inside your function

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

print("Your value array ", valuesArray)
Udaya Sri
  • 2,372
  • 2
  • 25
  • 35