How to identify specific values in JSON response
Asked Answered
I

1

0

I would like to obtain specific JSON response. For example, obtaining only the results (i.e. name and score) in the array with id 25 and 26. Is there like a WHERE clause in swift? I'm using Alamofire and SwiftyJSON if that helps.

Right now my code just pulls in all the values but I want to only have the results with id 25 and 26. Is that possible?

My code:

  Alamofire.request(.GET, endPoint).validate()
        .responseJSON { response in

  switch response.result {

  case .Success:
            if let value = response.result.value {
                let json = JSON(value)
                for (_,subJson):(String, JSON) in json {
                    if let date = subJson["start_date"].string{
                        self.date = date
                    }
                    if let building = subJson["building_name"].string{
                        self.building = building
                    }
                    if let jobId = subJson["schedule_job_id"].int {
                        self.jobIdArray.append(jobId)
                    }
                    if let tasks = subJson["tasks"].array{
                        for building in tasks {
                            Tasks.sharedInstance.datas = tasks
                            if let ratings = building["safety_ratings"].array{
                                for submission in ratings {
                                    if let score = submission["score"].string {
                                        self.scoreArray.append(score)
                                    }
                                    if let ratingId = submission["safety_rating_id"].int {
                                        self.ratingArray.append(ratingId)
                                    }
                                    if let submissionId = submission["submission_id"].int {
                                        self.subIdArray.append(submissionId)
                                    }
                                }
                            }
                        }
                    }
                }
                onCompletion()
            }
 case .Failure(let error):
        print("Request failed with error: \(error)")
        onError?(error)
    }
}  

UPDATE

    func getTask(onCompletion: () -> (), onError: ((NSError) -> ())? = nil) {

    guard let endPoint = Data.sharedInstance.weeklyEndpoint  else { print("Empty endpoint"); return }

    Alamofire.request(.GET, endPoint, encoding: .JSON)
        .validate()
        .responseJSON { response in

        switch response.result {

        case .Success:
            if let value = response.result.value {
                let json = JSON(value)
                for (_,subJson):(String, JSON) in json {
                    if let date = subJson["start_date"].string{
                        self.date = date
                    }
                    if let building = subJson["building_name"].string{
                        self.building = building
                    }
                    if let jobId = subJson["schedule_job_id"].int {
                        self.ratingArray.append(jobId)
                    }

                    let IDsYouWant: [Int] = [18, 27]

                    let tasksYouWant = subJson["tasks"].arrayValue.filter {IDsYouWant.contains($0["id"].intValue)}

                    for task in tasksYouWant {

                        if let ratings = task["safety_ratings"].array{
                            for submission in ratings {

                                if let score = submission["score"].string {
                                    let scoreResult = Int(score)
                                    self.ratingArray.append(scoreResult!)
                                }

                                if let ratingId = submission["safety_rating_id"].int {
                                    self.ratingArray.append(ratingId)
                                }

                                if let submissionId = submission["submission_id"].int {
                                    self.ratingArray.append(submissionId)
                                }

                            }
                        }
                    }

                    if let tasks = subJson["tasks"].array{
                            Tasks.sharedInstance.datas = tasks
                    }
                }

                print(self.ratingArray)
                onCompletion()
            }

        case .Failure(let error):
            print("Request failed with error: \(error)")
            onError?(error)
        }
    }      
}

When I print taskYouWant I get an empty array..

This is the JSON response from my GET https://codeshare.io/UqJMV

What I am looking for is the score, safety_rating_id where my submission_id is of x value. For example, to pull the array where submission_id is 27.

Iliad answered 31/5, 2016 at 8:33 Comment(3)
Not with JSON, no, however once you have parsed it to Objective-C collection classes, you have some options...Paten
Could you please include an actual snippet of your JSON? The one you've pasted is not valid. Thanks.Santossantosdumont
Hi @EricD I've updated my post with the JSON responseIliad
C
0

how about casting subJson["tasks"] to an array and then filtering it:

let IDsYouWant: [Int] = [25, 26]
let tasksYouWant = subJson["tasks"].arrayValue.filter {IDsYouWant.contains($0["id"].intValue)}

for task in tasksYouWant {
    //process task 25 and 26
}

hope that helps!

Chemaram answered 31/5, 2016 at 15:40 Comment(5)
Hi @Chemaram I'm getting an empty array .. Could you please help me? (updated code)Iliad
Which JSON are you trying to parse? The one you pasted in codeshare looks different and you need to update the keys to appropriate values to make it workChemaram
Apologies for the confusion I'm trying to parse the JSON in codeshare I've updated my values too. I'm only interested in the array with submission id 27 (My JSON gives me several arrays, I've updated my codeshare to reflect that)Iliad
Ok, again, in your codeshare you have inconsistent objects. The first couple of ones have "submission_id" as int: "submission_id" : 26 the one you marked you're interested in is string "submission_id" : "27" If id is a string then you need to put strings in IDsYouWant and filter closure should read {IDsYouWant.contains($0["id"].stringValue)}Chemaram
I'm still getting nil I think the issue is that the script cannot read the submission_id valueIliad

© 2022 - 2024 — McMap. All rights reserved.