[英]I have a data String with multiple JSON Objects, how can I store all JSON Objects from the String in an Array filled with objects?
[英]How can I remove all JSON objects that have a certain key/value pair from an array of JSON objects?
我想过滤这样的数据集:
例如这里有一些假数据集:
[
{
"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"],
}
任何帮助将不胜感激!
正如评论中已经提到的,您不能直接在 Swift 中的 JSON 对象上工作。 他们需要先转换。
您可以将 JSON 解析为 Swift object,然后执行过滤、分组等。
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(捕获错误)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.