1

How can I filter these json object? I mean I want print only patients whose id is equal to 3.

var patients: Array<AnyObject>? if let obj: AnyObject = manager?.responseObject as AnyObject? {
            if let pats = obj["patients"] as! Array<AnyObject>? {
                patients = pats
            }
        }

This is my printed variable

{
    patients =     (
                {
            city = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            district = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            firstname = fdfsdf;
            lastname = dsfgsdfg;
            "patient_id" = 1064;
            "patient_status" = 3;
            "register_id" = "\U0430\U043083040411";
        }
                {
            city = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            district = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            firstname = dwfw;
            lastname = dsfsdf;
            "patient_id" = 1056;
            "patient_status" = 1;
            "register_id" = "\U0443\U044399111134";
        }
}
1
  • if let pats = obj["patients"] as [String:Any]{patients = pats.filter{$0.patient_id ==3}} or something like that? Commented Oct 28, 2016 at 9:56

1 Answer 1

2

Please cast the types down as much as possible.

All types are more specific than AnyObject, JSON dictionaries are always [String:AnyObject] and JSON arrays are Array<[String:AnyObject]>. Use Array<AnyObject> only if the array contains another array or is more nested.

Filter the patients with the filter function.

var patients = Array<[String:AnyObject]>()

if let obj = manager?.responseObject as? [String:AnyObject] {
   if let pats = obj["patients"] as? Array<[String:AnyObject]> {
       patients = pats.filter { $0["patient_status"] as! Int == 3 } 
   }
}

Note: In Swift 3 AnyObject has been replaced with Any.

Sign up to request clarification or add additional context in comments.

Comments

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.