gpt4 book ai didi

arrays - 如何返回满足给定谓词的 Dictionary 值?

转载 作者:行者123 更新时间:2023-11-30 10:47:37 25 4
gpt4 key购买 nike

我无法解决下一个问题。我从 JSON 获取具有相同键和不同值的字典数组。例如:

{
"data": [{
"name": "Anna",
"features": {
"age": "18",
"hobby": "football"
}
}, {
"name": "Peter",
"data": {
"age": "16",
"hobby": "computer games"
}
}, {
"name": "Peter",
"data": {
"age": "25",
"hobby": "chess",
"job": "fireman"
}
}
],
"view": ["Peter", "Anna", "Peter"]
}

这是我的解码结构:

struct Object: Decodable {
let objectData: [DictionaryData]
let bjectView: [String]
}

struct DictionaryData: Decodable {
let name: String
let features: Features?
let data: DataClass?
}

struct DataContainer: Decodable {
let age, hobby: String
let job: String?
}

struct Features: Decodable {
let age, hobby: String
}

这就是我陷入困境的地方。我使用过滤器,但当我需要字典值时它返回 Bool:

    var items = [ModelItem]()
var singleObject: Object!

func jsonParsing(completionHandler: @escaping (([ModelItem], Error?) -> Void)) {

guard let url = URL(string: jsonUrlString) else { return }

URLSession.shared.dataTask(with: url) { (data, response, error) in

guard let data = data else { DispatchQueue.main.async {completionHandler([], error)}
return
}

do {
self.singleObject = try JSONDecoder().decode(Object.self, from: data)
let sequenceArray = self.singleObject.objectView
for i in sequenceArray {
if i == "Peter" {
if let objectName = self.singleObject?.objectData.filter({ return $0.name == "Peter"}) ... {
let firstItem = ModelFirstItem(text: ...) //here should be a value
self.items.append(firstItem)
}
}
else if i == "Anna" {
...
}
}
}
DispatchQueue.main.async {completionHandler(self.items, nil)}
} catch {
print("Error serializing json:", error)
}
} .resume()
}

我如何获得年龄、爱好和工作值(value)观?谢谢!

最佳答案

JSON 的可编码模型

struct Welcome: Codable {
let data: [Datum]
let view: [String]
}

struct Datum: Codable {
let name: String
let features: Feature?
let data: Data?
}
struct Data: Codable {
let age, hobby: String
let job: String?
}
struct Feature: Codable {let age, hobby: String}

解码 JSON

let decoder = JSONDecoder()
let decodedObject = try! decoder.decode(Welcome.self, from: JSON)
let filterdPeter = decodedObject.data.filter {$0.name == "Peter"}.map({$0.data})

filterdPeter.forEach {print($0)}

关于arrays - 如何返回满足给定谓词的 Dictionary 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55423071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com