Jay Strawn
Jay Strawn

Reputation: 215

Swift Codable: Array of Dictionaries

I have a JSON object from Yelp and I cannot figure out how to access the title in categories using Swift Codable. This is the JSON (with some elements removed for ease of reading):

{
    "businesses": [
        {
        "id": "fob-poke-bar-seattle-2",
        "name": "FOB Poke Bar",
        "is_closed": false,
        "review_count": 421,
        "categories": [
            {
                "alias": "poke",
                "title": "Poke"
            },
            {
                "alias": "salad",
                "title": "Salad"
            },
            {
                "alias": "hawaiian",
                "title": "Hawaiian"
            }
        ],
        "rating": 5,
        "coordinates": {
            "latitude": 47.6138005187095,
            "longitude": -122.343868017197
        },
        "price": "$$",
        "location": {
            "city": "Seattle",
            "zip_code": "98121",
            "country": "US",
            "state": "WA",
            "display_address": [
                "220 Blanchard St",
                "Seattle, WA 98121"
            ]
        },
    }

Here it is in JSON Viewer

I access first level properties like name easily, and I access lattitude and longitude like so:

class Business: Codable {

  var name: String
  var rating: Double
  var coordinates: Coordinates

  struct Coordinates: Codable {
    var latitude: Double
    var longitude: Double

    init(lat: Double, long: Double) {
      self.latitude = lat
      self.longitude = long
    }
  }

  init(name: String, rating: Double, coordinates: Coordinates) {
    self.name = name
    self.rating = rating
    self.coordinates = coordinates
    self.categories = categories
  }
}

Could anyone please point me in the right direction towards accessing categories -> title? Coordinates was easy to access but categories is an array of dictionaries. Thank you!

Upvotes: 6

Views: 6542

Answers (1)

vadian
vadian

Reputation: 285260

It's the same pattern like Coordinates except the value for categories is an array:

struct Root : Decodable {
    let businesses : [Business]
}

struct Business: Decodable {

    let name: String
    let rating: Int
    let coordinates: Coordinates

    let categories : [Category]

    struct Coordinates: Codable {
        let latitude: Double
        let longitude: Double
    }

    struct Category: Codable {
        let alias: String
        let title: String
    }
}

let root = try decoder.decode(Root.self, from: data)
for business in root.businesses {
        for category in business.categories {
            print(category.title)
    }
}

Upvotes: 10

Related Questions