json - Swift 根据查询字符串过滤包中的 Json 文件
问题描述
我正在从应用程序包中加载一个 json 文件,如下所示:
if let fileURL = Bundle.main.url(forResource: "Picker.bundle/Data/MyCodes", withExtension: "json") {
URLSession.shared.dataTask(with: fileURL) { (data, response, error) in
do {
if let d = data {
let decodedLists = try JSONDecoder().decode([Codes].self, from: d)
DispatchQueue.main.async {
self.code = decodedLists
}
} else {
print("No Data")
}
} catch {
print ("Error")
}
}.resume()
}
无论如何我可以应用过滤器,以便它只读取名称以某个字符串开头的代码
例子。
查询字符串将是“Can”,它将遍历 json 树并且只返回带有 Can i 他们的名字的孩子吗?
解决方案
解析JSON后,可以过滤结果,
struct Codes {
var title: String
}
DispatchQueue.main.async {
//filter codes if title starts with "Can"
self.code = decodedLists.filter { $0.title.hasPrefix("Can") }
//filter codes if title contains the substring "Can"
self.code = decodedLists.filter { $0.title.contains("Can") }
}
推荐阅读
- python - 如何修复 TypeError: Expected unicode, got pandas._libs.properties.CachedProperty
- matlab - 找到关于两个矩阵 X 和 Y 的 (x,y) 的最接近值
- java - Java随机生成5个数字并打印最大的
- python - Python AST - 容纳两个或更多子节点的运算符节点
- redis - 无法保存 Redis ACL 在日志中获得权限被拒绝
- string - 从字符串创建一个列表
- mysql - 使用 fluentd mysql-replicator 插件将单个 Mysql 数据复制到 Elasticsearch
- python - 如何使用 try-expect 跳过 selenium 无法使用 Selenium 和 Python 定位元素的情况
- pdf - Pandoc Markdown 到 PDF 和 SVG 图像导致“xdvipdfmx:fatal: pdf_link_obj(): pass invalid object.”?
- multithreading - 如何在不使用互斥锁的情况下从任意索引的多个线程写入可变切片?