Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let initialJSONString = """
- [
- {
- "id" : 1023,
- "price" : "89.50",
- "stock_quantity" : 7,
- "virtual" : false,
- "attributes" : [
- {
- "id" : 2,
- "option" : "XL",
- "name" : "Size"
- },
- {
- "id" : 1,
- "option" : "Black",
- "name" : "Color"
- }
- ],
- "sale_price" : "",
- "shipping_class_id" : 0
- },
- {
- "id" : 1022,
- "price" : "89.50",
- "stock_quantity" : 7,
- "virtual" : false,
- "date_on_sale_to" : null,
- "attributes" : [
- {
- "id" : 2,
- "option" : "XL",
- "name" : "Size"
- },
- {
- "id" : 1,
- "option" : "Virtual Pink/Black",
- "name" : "Color"
- }
- ],
- "sale_price" : "",
- "shipping_class_id" : 0
- }
- ]
- """
- struct Cloth: Codable {
- let id: Int
- let price: String
- let stockQuantity: Int
- let virtual: Bool
- let attributes: [Attributes]
- let salePrice: String
- let shippingClassId: Int
- struct Attributes: Codable {
- let id: Int
- let option: String //If you have limited values, you can use an enum String here
- let name: String
- }
- }
- func parseClothes() {
- let jsonData = initialJSONString.data(using: .utf8)!
- do {
- let decoder = JSONDecoder()
- decoder.keyDecodingStrategy = .convertFromSnakeCase
- let clothes = try decoder.decode([Cloth].self, from: jsonData)
- print(clothes)
- let filtered = clothes.filter { aCloth in
- let attributes = aCloth.attributes
- return attributes.contains { $0.name == "Color" && $0.option == "Black" }
- && attributes.contains { $0.name == "Size" && $0.option == "XL" }
- }
- print(filtered)
- } catch {
- print("Error: \(error)")
- }
- }
- parseClothes()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement