1

I am running into troubles updating my app as Alamofire and SwiftyJSON are not yet supporting Swift 3. I have a url that would return me json as follows:

{
    "products": [
        {
            "body_html":"",
            "created_at":"2016-03-02T13:56:18+03:00",
            "id":489759251,
            "handle":"product",
            "options":[
                {
                    "id":627488838,
                    "product_id":489759251,
                    "name":"Title",
                    "position":1,
                    "values":[
                        "Default Title"
                    ]
                }
            ],

        },

        {
            "body_html":"",
            "created_at":"2016-03-08T05:17:55+03:00",
            "id":530420915,
            "handle":"product-2",
            "options":[
                {
                    "id":6319359750,
                    "product_id":530420915,
                    "name":"Title",
                    "position":1,
                    "values":[
                        "Default Title"
                    ]
                }
            ],

        },
    ]
}

I need to be able to parse that json and list all returned products and be able to read any specific attribute and sub options of each.

I checked some other questions here and found several solutions and was able to get the json data and printed it as above. But, I couldn't parse it.

let shopUrl = "https://\(apiKey):\(password)@\(hostname)" + "/admin/products.json"

let url = URL(string: shopUrl)
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
    if error != nil {
        print(error)
    } else {
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
            print(json)
        } catch let error as NSError {
            print(error)
        }
    }
}).resume()

Any help?

8
  • That's not JSON, that's the output of a print line representing the result of the deserialization. Commented Sep 21, 2016 at 7:23
  • yes, that's right. I thought providing the print output will make it easier to provide me help Commented Sep 21, 2016 at 7:28
  • I know it doesn't help answering your question but Alamofire4.0 does have Swift 3 support. SwiftyJSON doesn't have any Swift 3 support apart from a branch for one of the early betas.. Commented Sep 21, 2016 at 7:30
  • @donnywals exactly, that's why I am stuck here :( Commented Sep 21, 2016 at 7:31
  • Better post the raw JSON string. Commented Sep 21, 2016 at 7:36

2 Answers 2

1

To loop over all of the products you need to extract and cast it to the correct type. In this case an array of [String: Any].

I extracted the relevant bit of code and cleaned it up a bit to make this answer more readable.

guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any],
    let products = json["products"] as? [[String: Any]]
    else { return }

for product in products {
    guard let id = product["id"] as? Int,
        let options = product["options"] as? [[String: Any]]
        else { return }

    print(id)
    print(options)
}
Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to get the count of products?
Thank you very much donnywals
0

This parses the JSON, the root object is a dictionary, the objects for products and options are arrays. One value respectively is printed as an example.

if let jsonObject = try JSONSerialization.jsonObject(with:data, options: []) as? [String:Any] {
  print(jsonObject)
  if let products = jsonObject["products"] as? [[String:Any]] {
    for aProduct in products {
      print(aProduct["created_at"])
      if let options = aProduct["options"] as? [[String:Any]] {
        for option in options {
          print(option["product_id"])
        }
      }
    }
  }
}

1 Comment

I'd advice to use guard instead of all these if let constructions. The nesting will quickly lead to the infamous pyramid of doom..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.