Filter data in SwiftyJson

I have one SwiftyJson object.

I cannot filter this array. I tried this solution https://stackoverflow.com> . But my json format is different from why it doesn't work.

[
    {
        "name": "19860",
        "header": {
            "start_time": "1519270200",
            "end_time": "1519299000",
            "state": "lunch"
        },
        "alerts": "1",
        "venue": {
            "location": "Delhi, India",
            "timezone": "+05:30"
        },
        "srs_category": [
            0,
            1
        ]
    },
    {
        "name": "19861",
        "header": {
            "start_time": "1519270200",
            "end_time": "1519299000",
            "state": "Dinner"
        },
        "alerts": "1",
        "venue": {
            "location": "Mumbai, India",
            "timezone": "+05:30"
        },
        "srs_category": [
            1,
            3
        ]
    },
    {
        "name": "19862",
        "header": {
            "start_time": "1519270200",
            "end_time": "1519299000",
            "state": "lunch"
        },
        "alerts": "1",
        "venue": {
            "location": "Surat, India",
            "timezone": "+05:30"
        },
        "srs_category": [
            0,
            2
        ]
    }
]

I want to find the object that contains srs_category 1. I know that this is possible by looping and state. But I want through NSPredicate. If possible, please help me.

Thank.

0
source share
2 answers

Use a quick function, not NSPredicate

datarepresents an object dataobtained from somewhere

do {
    if let json = try JSONSerialization.jsonObject(with:data) as? [[String:Any]] {
        let srsCategory1 = json.first(where: { dict -> Bool in
            guard let array = dict["srs_category"] as? [Int] else { return false }
            return array.contains(1)
        })
        print(srsCategory1 ?? "not found")
    }
} catch {
    print(error)
}

, , first filter. .

+1

SwiftyJSON:

    let filtered = JSON(yourArray).arrayValue.filter({
        $0["srs_category"].arrayValue.map({ $0.intValue }).contains(1)
    })
+2

All Articles