过滤JSON数据并打印它

时间:2017-05-22 10:15:01

标签: ios arrays json swift

我在快速代码中成功parse JSON data,但我想打印具有特定值的代码。现在代码vc.packages打印所有,但我只想打印那些:

  • “typeCode”为FULL,“validTo”有值,“stateCode”有效

我如何在我的代码中检查并分别打印它?

func unzipPackage() {

    let vc = storyboard?.instantiateViewController(withIdentifier: "LoadingScreenController") as! LoadingScreenController

    let popup = STPopupController(rootViewController: vc)
    popup.style = .formSheet
    popup.hidesCloseButton = false
    popup.navigationBarHidden = true
    popup.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    popup.containerView.layer.cornerRadius = 4
    popup.present(in: self, completion: {

        DemosClient.sharedInstance.requestDataPackage()
            .then { response -> Void in

                vc.contentSizeInPopup = CGSize(width: 600, height: 800)
                vc.landscapeContentSizeInPopup = CGSize(width: 600, height: 800)


                vc.titles = (self.parseJSON(response: response))
                print(vc.titles)
                vc.packages = response["results"] as? [[String:Any]] ?? []


                print(vc.packages)

            }
            .catch { error in

                print(error)
        }

        vc.loadData()
        vc.startTimer()


    })

2 个答案:

答案 0 :(得分:2)

为此,您可以filter results数组,然后将filter的结果分配给packages

let results = response["results"] as? [[String:Any]] ?? []
vc.packages = results.filter {
    return ($0["typeCode"] as? String == "FULL") && 
           ($0["validTo"] != nil) && 
           ($0["stateCode"] as? String == "valid")
}

答案 1 :(得分:1)

您需要解析字典数组并检查键及其对应的值。这段代码应该可以解决问题。我没有测试过,但应该可以正常工作。

vc.packages = response["results"] as? [[String:Any]] ?? []

let filteredPackages = [[String:Any]]()
for package in vc.packages {
    guard let typeCode = package["typeCode"] as? String, typeCode == "FULL" else { continue }
    guard let stateCode = package["stateCode"] as? String, stateCode == "valid" else {continue}
    guard let validTo = package["validTo"] as? String, validTo != "" else {continue}
    filteredPackages.append(package)
}

print(filteredPackage)