Aniket Patil Aniket Patil - 3 months ago 10
iOS Question

Retrieve specific Array from JSON in swift in the form of Array of Keys and Values?

JSON :

{
"11/08/22":[
{
"Bill Gates":"Microsoft",
"Steve Balmer":"Microsoft"
}],

"13/08/22":[
{
"Tim Cook":"Apple",
"Jony Ive":"Apple"
}]

}


Swift Code :

let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
do {
if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {


print(jsonResult)

//Get Result into Seperate Arrays
let keys = jsonResult.flatMap(){ $0.0 as? String }
let values = jsonResult.flatMap(){ $0.1 as? String }

}
} catch let error as NSError {
print(error)
}

})
jsonQuery.resume()


Requirements :

If i pass from program "11/08/22", I should be able to get all keys and values in the form of Array of String of only that array named "11/08/22" .

Better Explanation :

It should go into 11/08/22 and it should retrieve "Bill Gates","Steve Balmer" as Keys and "Microsoft" As a value in two separate arrays

Answer
let keys=jsonResult["11/08/22"]?.allKeys as? [String];                       
let values=jsonResult["11/08/22"]?.allValues as? [String];

It was as simple as this