0

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?

1
  • 3
    Why would you change the JSON to contain so much duplicate data? Commented Nov 5, 2018 at 20:42

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.