Myreaux Myreaux - 2 months ago 37
JSON Question

Parsing JSON with dynamic keys in Swift

I am trying to parse JSON files from an url. This JSON has a key that is dynamic, in that it changes per file. Right now my code looks like this:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)


// Parsing
if let stations = json["observations"]!!["-10019482"] as? [[String: AnyObject]] {

for observation in stations {

if let name = observation["stationname"] as? String {

if let temperatuuri = observation["Temperature"] as? String {
if let windSpeed = observation["WindSpeedMS"] as? String {
print(name, temperatuuri, windSpeed,"m/s")
self.temperature.text = String(temperatuuri)
}
}

}

}
}


"-10019482" is the part that changed dynamically and the key name cannot be predicted. However, I know that it is always the first key inside "observations".

How would I do the same, but without searching for a specific key name?

Answer

Since json["observations"] is a dictionary you could do something like this to obtain it's first key

guard let dict = json["observations"] as? [String: AnyObject],
    let firstKey = dict.keys.first else { return }

print(firstKey) // should print the first key found in the observations dictionary