gpt4 book ai didi

swift - 如何映射和过滤低于特定数字的 JSON 嵌套数据字典?

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

我有一个静态 JSON 文件,并且正在成功解码它。然而,我真的很难正确存储它,因为它嵌套了几层深。目前控制台打印出[“汉密尔顿”、“彻姆赛德”、“库帕鲁”]

但是,我需要它来过滤并返回每个郊区中低于 500000 的值。所以像这样的东西会很棒。

“汉密尔顿”
“oneBRU”:341000,
“twoBRU”:480000

“彻姆赛德”
“oneBRU”:320000,
“两个BRU”:255000,
“三布鲁”:435000,
“twoBRH”:400000

静态 JSON 文件位于底部。非常感谢

var suburbsJson: [Suburb] = []

struct ResponseData: Codable {
var suburbs: [Suburb]
}

struct Suburb : Codable {
var _id: Int
var name: String
var postcode: Int
var prices: SuburbPrices
}

struct SuburbPrices: Codable {
let oneBRU: Int
let twoBRU: Int
let threeBRU: Int
let twoBRH: Int
let threeBRH: Int
let fourBRH: Int
}

func loadJson(filename fileName: String) -> [Suburb]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(ResponseData.self, from: data)
self.suburbsJson = jsonData.suburbs

let suburb = suburbsJson.map { $0.name }
print(suburb)

// print only suburbs below 500000



return jsonData.suburbs
} catch {
print("error:\(error)")
}
}
return nil
}

JSON 文件

{
"suburbs": [
{
"_id": 1,
"name": "Hamilton",
"postcode": 4007,
"prices":
{
"oneBRU": 341000,
"twoBRU": 480000,
"threeBRU": 880000,
"twoBRH": 555000,
"threeBRH": 945000,
"fourBRH": 1200000
}
},
{
"_id": 2,
"name": "Chermside",
"postcode": 4032,
"prices":
{
"oneBRU": 320000,
"twoBRU": 255000,
"threeBRU": 435000,
"twoBRH": 400000,
"threeBRH": 585000,
"fourBRH": 860000
}
},
{
"_id": 3,
"name": "Coorparoo",
"postcode": 4151,
"prices":
{
"oneBRU": 323000,
"twoBRU": 359750,
"threeBRU": 535000,
"twoBRH": 500000,
"threeBRH": 750000,
"fourBRH": 970000
}
}
]
}

最佳答案

如果您只需要打印值,您可以执行以下操作:

func loadJson(filename fileName: String) -> [Suburb]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(ResponseData.self, from: data)
self.suburbsJson = jsonData.suburbs

// print only suburbs below 500000
jsonData.suburbs.forEach { suburb in
print(suburb.name)
if suburb.prices.oneBRU < 500000 {
print("One BRU: \(suburb.prices.oneBRU)")
}
if suburb.prices.twoBRU < 500000 {
print("Two BRU: \(suburb.prices.twoBRU)")
}
if suburb.prices.threeBRU < 500000 {
print("Three BRU: \(suburb.prices.threeBRU)")
}
if suburb.prices.twoBRH < 500000 {
print("Two BRH: \(suburb.prices.twoBRH)")
}
if suburb.prices.threeBRH < 500000 {
print("Three BRH: \(suburb.prices.threeBRH)")
}
if suburb.prices.fourBRH < 500000 {
print("Four BRH: \(suburb.prices.fourBRH)")
}
}
return jsonData.suburbs
} catch {
print("error:\(error)")
}
}
return nil
}

关于swift - 如何映射和过滤低于特定数字的 JSON 嵌套数据字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453376/

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