Vix Hunk
Vix Hunk

Reputation: 323

Fetching data from multi level JSON

I am having issue fetching products "name" from a json file.

here is json output

and here is my code so far. and it prints complete json. I just want to fetch name of the products from this file.

guard let url = URL(string: "https://URL/get_products.php") else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let dataResponse = data,
              error == nil else {
              print(error?.localizedDescription ?? "Response Error")
              return }
        do{
            let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: [])
            print(jsonResponse)
         } catch let parsingError {
            print("Error", parsingError)
       }
    }
    task.resume()

Upvotes: 0

Views: 83

Answers (1)

vadian
vadian

Reputation: 285069

The structure is pretty clear, values next to string keys are dictionaries, next to ordinal numbers are arrays:

if let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse) as? [String:Any],
   let data = jsonResponse["data"] as? [[String:Any]] {
    for anItem in data {
        if let products = anItem["products"] as? [[String:Any]] {
            for product in products {
                if let name = product["name"] as? String {
                    print(name)
                }
            }   
        }  
    }
}

A better way is to parse the JSON into structs with JSONDecoder

Upvotes: 2

Related Questions