Caleb Rudnicki
Caleb Rudnicki

Reputation: 395

Parse JSON Swift 3 Dictionary

I am attempting to try to get all 31 teams from the NHL from this JSON link. Here is a look at what the file looks like:

{
   "sports":[
      {
         "name":"hockey",
         "slug":"hockey",
         "id":70,
         "uid":"s:70",
         "leagues":[
            {
               "name":"National Hockey League",
               "slug":"nhl",
               "abbreviation":"nhl",
               "id":90,
               "uid":"s:70~l:90",
               "groupId":9,
               "shortName":"NHL",
               "teams":[
                  {
                      ...team info....
                  }......

I currently have this do statement in function trying to loop thru all 31 entries in the "teams" array:

if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
     if let entries: NSArray = parsedData["sports"] as! NSArray  {
        for entry in entries {
            //work with data
        }
     }
}

I know I have to dig a bit deeper on the "if let entries" line, but I can't seem to get the data I want. Thanks in advance.

Upvotes: 2

Views: 2913

Answers (1)

vadian
vadian

Reputation: 285270

First of all, why do so many tutorials suggest / people use .mutableContainers although the object is never going to be mutated and ironically the result is mostly assigned to an immutable object?

Don't do that. Pass no options by omitting the parameter.

Second of all don't fight Swift's strong type system. Use native collection types Array and Dictionary and do not annotate types the compiler can infer.

Let`s create a type alias for convenience:

typealias JSONDictionary = [String:Any]

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? JSONDictionary,

The value for key sports is an array (represented by [])

   let sports = parsedData["sports"] as? [JSONDictionary] {

Enumerate the array and get the value for key leagues which is also an array

      for sport in sports {
          print("sport ", sport["name"] as? String ?? "n/a")
          if let leagues = sport["leagues"] as? [JSONDictionary] {

Do the same with leagues and get the teams

             for league in leagues {
                print("league ", league["name"] as? String ?? "n/a")
                if let teams = league["teams"] as? [JSONDictionary] {
                for team in teams {

Parsing JSON is pretty easy, there are only two collection types and four value types.

                }  
             }
          }
      }
   }
}

Upvotes: 2

Related Questions