1

When I'm using double scopes here [[String: Any]] jsonArray is being empty How to make it works properly?

I tried to use [String: Any] it works, but now I can't use [ 0 ]["aaData"](for example) it says "Cannot subscript a value of type '[String : Any]' with an index of type 'Int'".

func displayURL(){

   let myURLAdress = "http://www.ucrf.gov.ua/wp-admin/admin-ajax.php?action=get_wdtable&table_id=1&sEcho=3&iColumns=10&sColumns=&iDisplayStart=0&iDisplayLength=-1&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&mDataProp_3=3&mDataProp_4=4&mDataProp_5=5&mDataProp_6=6&mDataProp_7=7&mDataProp_8=8&mDataProp_9=9&sSearch=&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=true&sSearch_2=&bRegex_2=false&bSearchable_2=true&sSearch_3=&bRegex_3=false&bSearchable_3=true&sSearch_4=&bRegex_4=false&bSearchable_4=true&sSearch_5=&bRegex_5=false&bSearchable_5=true&sSearch_6=&bRegex_6=false&bSearchable_6=true&sSearch_7=&bRegex_7=false&bSearchable_7=true&sSearch_8=&bRegex_8=false&bSearchable_8=true&sSearch_9=LTE-2600&bRegex_9=false&bSearchable_9=true&sRangeSeparator=~&_=1545585236527"
        let myURL = URL(string: myURLAdress)

    let task = URLSession.shared.dataTask(with: myURL!) { (data, response, error) in
        guard let dataResponse = data,
            error == nil else {
                print(error?.localizedDescription ?? "Response Error")
                return }
        do{
            //here dataResponse received from a network request
            let jsonResponse = try JSONSerialization.jsonObject(with:
                dataResponse, options: [])
            //print(jsonResponse)


            guard let jsonArray = jsonResponse as? [[String: Any]] else {
                return
            }
            print(jsonArray)


        } catch let parsingError {
            print("Error", parsingError)
        }

    }
    task.resume()
    }
}
timbre timbre
  • 12,648
  • 10
  • 46
  • 77

1 Answers1

1

You need

let jsonResponse = try JSONSerialization.jsonObject(with:dataResponse, options: []) as! [String:Any]
guard let jsonArray = jsonResponse["aaData"] as? [[String]] else {
     return
}

Your json structure

{
    "sEcho": 3,
    "iTotalRecords": "174289",
    "iTotalDisplayRecords": "1448",
    "aaData": [[ "" ,"" , ""]]
}

BTW always recommend

struct Root : Codable {
    let sEcho: Int
    let iTotalRecords, iTotalDisplayRecords: String
    let aaData: [[String]]
}

Then

let res = try JSONDecoder().decode(Root.self,from:data)
let arr = res.aaData
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87