我正在从API获取数据,我需要根据“ total_price”标签过滤字典数组,现在的条件是我只希望价格在“ 35.0”到“ 55.0”之间的那些航班
{
airline = 9W;
"available_seats" = "<null>";
bags = (
);
currency = USD;
destination = 38551;
origin = 39232;
"price_details" = {
};
"rate_plan_code" = WIP;
routes = (
);
taxes = "17.51";
"total_price" = "31.7";
}
由于total_price标签以字符串形式出现,因此我不确定如何使用谓词等对其进行过滤。我需要过滤json响应本身,因此未为此API响应创建任何模型。
答案 0 :(得分:1)
由于您要过滤价格,因此我假设您有一个数组,并且在我的代码中进一步假设此数组位于带有键“航班”的字典中,因此您需要将此键更改为您拥有的键
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
if let flights = json["flights"] as? [[String: Any]] {
let filtered = flights.filter {
if let str = $0["total_price"] as? String, let price = Double(str) {
return price >= 35.0 && price <= 55.0
}
return false
}
print(filtered.count) // replace with more meaningful code :)
}
}
} catch {
print("Decode failed: \(error)")
}