Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter SwiftyJson Data

I have some JSON Data. This is an Array of Dictionaries The SwiftyJson Array is called jsonObj["Customer"] and looks like:

[{
    "kode_customer": 1,
    "nama_customer": "Logam Jaya, UD",
    "alamat_customer": "Rajawali No 95",
    "kodepos": 60176,
    "kode_provinsi": 11,
    "gps_lat": -7.233834999999999,
    "gps_long": 112.72964666666667
}, {
    "kode_customer": 2,
    "nama_customer": "Terang, TK",
    "alamat_customer": "Raya Dukuh Kupang 100",
    "kodepos": 60225,
    "kode_provinsi": 11,
    "gps_lat": -7.285430000000001,
    "gps_long": 112.71538333333335
}, {
    "kode_customer": 3,
    "nama_customer": "Sinar Family",
    "alamat_customer": "By Pass Jomin No 295",
    "kodepos": 41374,
    "kode_provinsi": 9,
    "gps_lat": -6.4220273,
    "gps_long": 107.4748978
}, {
    "kode_customer": 4,
    "nama_customer": "Lancar Laksana, TB",
    "alamat_customer": "Jendral Sudirman No 69",
    "kodepos": 41374,
    "kode_provinsi": 9,
    "gps_lat": -6.4220273,
    "gps_long": 107.4748978
}]

now i want fo filter the Data in this Way

let filterdData = self.jsonObj["Customer"].filter({(JSON) -> Bool in
return self.jsonObj["Customer"]["kodepos"] < 6000
})

I want to see now two Results. But this does not work, i think because of the missing 'index' between

self.jsonObj["Customer"] and ["kodepos"]

Or let me say it in another way

print (self.jsonObj["Customer"]["kodepos"]) ...i just want to see all Values for kodepos

How is it possible to filter the Data in SwiftyJson.

like image 452
Marc Avatar asked Jan 28 '26 15:01

Marc


1 Answers

Try with the below code snippet if you are using SwiftyJSON. It works perfectly.

let jsonObj = some JSON 
let jobj = jsonObj.arrayValue
if !jobj.isEmpty {
   let j = jobj.filter({ (json) -> Bool in
       return json["country"].stringValue == "US"; })
   print ("filterdData: \(j)")
}

Note: jobj should be .arrayValue, otherwise it won't work.

like image 59
Princess Avatar answered Jan 31 '26 03:01

Princess