1

With a JSON object as below, is it possible to filter only IOS related content? I'm open to any method, i.e. a for-in loop or .filter?

For example I would want to filter so that I return content only when the platform key is a match for "IOS", in which case I would get:

  • Title 1
  • question 1b
  • IOS

The difficulty is that the title should only be printed if the platform match is successful, and I can't see a way of achieving this with a regular nested for in loop.

[
  {
    "title": "Title 1",
    "faqs": [
      {
        "question": "question 1a",
        "platform": "ANDROID"
      },
      {
        "question": "question 1b",
        "platform": "IOS"
      }
    ]
  },
  {
    "title": "Title 2",
    "faqs": [
      {
        "question": "question 2a",
        "platform": "ANDROID"
      },
      {
        "question": "question 2b",
        "platform": "WEB"
      }
    ]
  }
]

2 Answers2

0

Simple (Swift 3) solution, data is the JSON string as Data:

  do {
    if let jsonObject = try JSONSerialization.jsonObject(with:data, options: []) as? [[String:Any]] {
      for item in jsonObject {
        if let title = item["title"] as? String,
           let faqs = item["faqs"] as? [[String:String]],
           let iOSFaqs = faqs.filter({$0["platform"] == "IOS"}).first {
             print(title)
             print(iOSFaqs)
        }
      }
    }
  } catch let error as NSError {
    print(error)
  }
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks. I like the solution, but unfortunately we are not able to update to Swift 3 yet. I should have been explicit about that, sorry. –  Sep 27 '16 at 11:49
  • In Swift 2 there is only one little change `try NSJSONSerialization.JSONObjectWithData(data, options: [])` and you can omit the second and third `let` in the optional binding chain. – vadian Sep 27 '16 at 15:10
0

You can use NSPredicate to filter arrays of dictionaries. You can refer to these older questions for examples. This is not exactly "pure swift way", but gets the job done. The code is in Objective C, but it can be easily translated into Swift syntax. If you need help with that, I can extend the answer later. Link 1 Link 2

Community
  • 1
  • 1
hybridcattt
  • 3,001
  • 20
  • 37