【问题标题】:Filter SwiftyJson Data过滤 SwiftyJson 数据
【发布时间】:2016-12-14 04:47:45
【问题描述】:

我有一些 JSON 数据。这是一个字典数组 SwiftyJson 数组被称为 jsonObj["Customer"] 并且看起来像:

[{
    "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
}]

现在我想以这种方式过滤数据

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

我现在想查看两个结果。但这不起作用,我认为是因为

之间缺少“索引”
self.jsonObj["Customer"] and ["kodepos"]

或者让我换个方式说

print (self.jsonObj["Customer"]["kodepos"]) ...我只想查看 kodepos 的所有值

如何在 SwiftyJson 中过滤数据。

【问题讨论】:

  • 我也有同样的问题,你的解决方法了吗?

标签: arrays swift dictionary filter swifty-json


【解决方案1】:

如果您使用的是 SwiftyJSON,请尝试以下代码 sn-p。它完美地工作。

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)")
}

注意:jobj应该是.arrayValue,否则不起作用。

【讨论】:

    【解决方案2】:

    一种方法是使用 SwiftyJSON 对象的 .arrayValue 来创建过滤器

    let customers = self.jsonObj["Customer"].arrayValue
    let filterdData = customers.filter(){
        item = $0
        return item["Customer"]["kodepos"].intValue < 6000    
    }
    

    请参阅 SwiftyJSON 存储库中的下标部分 https://github.com/SwiftyJSON/SwiftyJSON#subscript

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多