Reputation: 4067
The JSON looks like this:
{
"00AK": {
"icao": "00AK",
"iata": "",
"name": "Lowell Field",
"city": "Anchor Point",
"country": "US",
"elevation": 450,
"lat": 59.94919968,
"lon": -151.695999146,
"tz": "America\/Anchorage"
},
"00AL": {
"icao": "00AL",
"iata": "",
"name": "Epps Airpark",
"city": "Harvest",
"country": "US",
"elevation": 820,
"lat": 34.8647994995,
"lon": -86.7703018188,
"tz": "America\/Chicago"
},
"00AZ": {
"icao": "00AZ",
"iata": "",
"name": "Cordes Airport",
"city": "Cordes",
"country": "US",
"elevation": 3810,
"lat": 34.3055992126,
"lon": -112.1650009155,
"tz": "America\/Phoenix"
}
}
As you can see the keys varies "00AK", "00AL", "00AZ", and so on. How do I parse this format of JSON?
Upvotes: 1
Views: 1563
Reputation: 793
You could try the below snippet:
func parseData() {
let jsonData = Data() /// your actual response data goes here...
do {
let dict = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
guard let swiftDict = dict as? [String : Any] else {
print("Not a valid response")
return
}
for (key, value) in swiftDict {
guard let valueDict = value as? [String: Any] else {
/// handle improper response here
return
}
/// Got the actual dictionary in 'valueDict'...
}
}
catch {
/// handle parsing error here
}
}
Upvotes: 0
Reputation: 11
So here it is I declare one structure as following
struct Model {
var iaco: String?
var iata: String?
var name: String?
var city: String?
var country: String?
var elevation: Int?
var lat: Double?
var lon: Double?
var tz: String? }
Then declare on array to hold the response result
var listOfModels = Array<Model>()
Then take a list of keys from response Dictionary and iterate over it to get result and store it in array
handleResponse { (response) in
for key in response.keys {
let dict = response[key] as? [String:Any]
var model = Model()
model.iaco = dict?["icao"] as? String
model.iata = dict?["iata"] as? String
model.name = dict?["name"] as? String
model.city = dict?["city"] as? String
model.country = dict?["country"] as? String
model.elevation = dict?["elevation"] as? Int
model.lat = dict?["lat"] as? Double
model.lon = dict?["lon"] as? Double
model.tz = dict?["tz"] as? String
listOfModels.append(model)
}
}
response.keys is used to get list of keys from dictionary.
Upvotes: 0
Reputation: 3802
let jsonData = //JSON DATA HERE
do {
let dict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! NSDictionary
for (key, value) in dict {
let subDict = value as! NSDictionary
//Then you can access the values from subDict
} catch {
//ERROR HANDLING
}
Upvotes: 1