Ankit Baid Ankit Baid - 1 month ago 24
Swift Question

how to access array inside json object in swift

Can't access json object which is array inside json object
i want to access data from json object which have array inside array
and that json file is also uploaded
so pls can anyone check and help me how to get "weather.description"
data

override func viewDidLoad() {
super.viewDidLoad()

let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

if error != nil {
print("some error occured")
} else {

if let urlContent = data {

do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

let newValue = jsonResult as! NSDictionary

print(jsonResult)

let name = newValue["name"]
//Here i am getting name as variable value

//this is not working
let description = newValue["weather"]??[0]["description"]

//this is not working
let description = newValue["weather"]!![0]["description"]

print()

}catch {
print("JSON Preocessing failed")
}

}
}
}
task.resume()

}


can anyone help me to get that data from weather.description

Answer

I have edited your code a bit, and added a few comments. Basiclly, lets check for the types of your response structure, and get the desired value.

let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print("some error occured")
            } else {

                if let urlContent =  data {

                    do{
                        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                        // I would not recommend to use NSDictionary, try using Swift types instead
                        guard let newValue = jsonResult as? [String: Any] else {
                            print("invalid format")
                            return
                        }

                        // Check for the weather parameter as an array of dictionaries and than excess the first array's description
                        if let weather = newValue["weather"] as? [[String: Any]], let description = weather.first?["description"] as? String {
                            print(description)
                        } 

                    }catch {
                        print("JSON Preocessing failed")
                    }
                }
            }
        }
        task.resume()