我想像这样过滤数据集:
例如,这是一些假数据集:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Donna",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Tia",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tuxedo"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
我想过滤出所有包含"livesInCity": false
的内容:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
我该怎么做?这可能吗?
我相信在python中是这样的,但是我不知道如何开始使用Swift:
people = [person for person in people if person.livesInCity == True]
此外,如何过滤上面的数据集看起来像这样-我想按名称类型进行分类。
{
"tabby": ["Sakura", "Linn"],
"tuxedo": ["Dora"],
}
任何帮助将不胜感激!
答案 0 :(得分:1)
正如评论中已经提到的那样,您不能直接在Swift中处理JSON对象。他们需要先进行转换。
您可以将JSON解析为Swift对象,然后执行过滤,分组等。
struct Person: Codable {
let name: String
let hasChildren: Bool
let livesInCity: Bool
let pets: [Pet]
}
struct Pet: Codable {
let cats: [String]
let type: String
}
let jsonStr = "[{"name": "Sakura", ..." // your JSON string
let jsonData = jsonStr.data(using: .utf8)!
let parsedObjects = try! JSONDecoder().decode([Person].self, from: data)
然后,您可以过滤您的parsedObjects:
let filteredObjects = parsedObjects.filter({ person in person.livesInCity == true })
或更短版本( swiftier ):
let filteredObjects = parsedObjects.filter { $0.livesInCity }
您也可以尝试按宠物类型分组:
var groupedDict = [String:[String]]()
filteredObjects.forEach{ person in
person.pets.forEach { pet in
if let _ = groupedDict[pet.type] {
groupedDict[pet.type]!.append(person.name)
} else {
groupedDict[pet.type] = [person.name]
}
}
}
print(groupedDict)
//prints ["tabby": ["Sakura", "Linn"], "tuxedo": ["Dora"]]
如果您想随时将对象转换回JSON,可以使用:
let dictData = try! JSONEncoder().encode(groupedDict)
let dictStr = String(data: dictData, encoding: .utf8)!
print(dictStr)
//prints {"tabby":["Sakura","Linn"],"tuxedo":["Dora"]}
注意
为简单起见,在解码/编码对象时,我使用了强制可选展开(!
)。您可能需要改用do-try-catch(以捕获错误)。