How to decode a nested JSON with many unique keys in Swift?
In this case I recommend to decode the JSON as dictionaries [String:[String]]
struct WeekendMenu: Decodable { private enum CodingKeys : String, CodingKey { case brunch = "Brunch", dinner = "Dinner" } let brunch: [String:[String]] let dinner: [String:[String]]}
Enumerate the dictionaries, sort the keys to get the same order
let result = try JSONDecoder().decode(WeekendMenu.self, from: data)for key in result.brunch.keys.sorted() { print(key, result.brunch[key]!)}for key in result.dinner.keys.sorted() { print(key, result.dinner[key]!)}
Alternatively write a custom initializer to decode the dictionaries into a custom struct Category
, the key becomes the name
, the value becomes the dishes
array.
struct WeekendMenu: Decodable { private enum CodingKeys : String, CodingKey { case brunch = "Brunch", dinner = "Dinner" } let brunch: [Category] let dinner: [Category] init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let brunch = try container.decode([String:[String]].self, forKey: .brunch) let brunchKeys = brunch.keys.sorted() self.brunch = brunchKeys.map { Category(name: $0, dishes: brunch[$0]!) } let dinner = try container.decode([String:[String]].self, forKey: .dinner) let dinnerKeys = dinner.keys.sorted() self.dinner = dinnerKeys.map { Category(name: $0, dishes: dinner[$0]!) } }}struct Category { let name : String let dishes : [String]}