使用如下的JSON对象,是否可以仅过滤IOS相关内容?我对任何方法都开放,即for-in循环或.filter?
例如,我想过滤以便仅在平台密钥与“IOS”匹配时返回内容,在这种情况下我会得到:
难点在于,只有在平台匹配成功的情况下才能打印标题,并且我无法通过常规嵌套for循环来看到实现此目的的方法。
[
{
"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"
}
]
}
]
答案 0 :(得分:0)
简单(Swift 3)解决方案,data
是JSON字符串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)
}
答案 1 :(得分:0)