harkul
harkul

Reputation: 11

Swift Codable, array value as key

So this is my JSON:

{
 "items": [{
    "name": "Item 1",
    "description": "This is Item 1",
    "categories": ["Category1", "Category2", "Category3", "Category4"],
    "size": ["M", "L"]
 },{
    "name": "Item 2",
    "description": "This is Item 2",
    "categories": ["Category1", "Category3", "Category4"],
    "size": ["M"]
 }]
}

I can read and print it perfectly fine

However, I want to change this structure to this one where each item is separated by category and size, and where the categories are used as keys.

{
 "categories": {
  "category1": [{
   "name": "Item 1",
   "description": "This is Item 1",
   "size": "M"
},{
   "name": "Item 1",
   "description": "This is Item 1",
   "size": "L"
},{
   "name": "Item 2",
   "description": "This is Item 2",
   "size": "M"
}...],
 "category2": [{
  ...
}]
}

I've created the following data structure but I'm not quite sure how to continue:

struct Categories: Codable {
 let category: String
 let items: [Item]

 struct Item: Codable {
  let name, description, size: String
 }
}

Is Codable the right solution for this? If so; how would I go on to achieve this?

Upvotes: 0

Views: 238

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

For your current json you need

struct Root: Codable {
    let categories: [String:[Item]]
}

struct Item: Codable {
    let name, description, size: String
}

But I think it's better to make it like this

{

    "category1": [{
       "name": "Item 1",
       "description": "This is Item 1",
       "size": "M"
       },{
       "name": "Item 1",
       "description": "This is Item 1",
       "size": "L"
       },{
       "name": "Item 2",
       "description": "This is Item 2",
       "size": "M"
    }],
    "category2": [{

    }]

}

Which will make you do this

let res = try? JSONDecoder().decode([String:[Item]].self,from:jsonData)

Without the Root struct and the useless categories key

Upvotes: 1

Related Questions