json - 过滤 JSON 数组以显示多个或单个键值
问题描述
这个块允许我选择一种货币并返回模型中声明的所有 API 值。id
, symbol
, name
, price
,marketCap
等等。
界面
let data = rawResponse.data
if let eth = data.filter({ (item) -> Bool in
let cryptocurrency = item.value.symbol
return cryptocurrency == "ETH"
}).first {
print(eth)
}
我需要灵活地只返回一个值,例如price
. 我可以注释掉结构的所有属性,但价格除外,但这会限制功能。
有人告诉我我可以let cryptocurrency = item.value.symbol
与return cryptocurrency == "ETH"
etc 进行比较,但我不确定如何做到这一点。
模型
struct RawServerResponse : Codable {
var data = [String:Base]()
private enum CodingKeys: String, CodingKey {
case data
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let baseDictionary = try container.decode([String:Base].self, forKey: .data)
baseDictionary.forEach { data[$0.1.symbol] = $0.1 }
}
}
struct Base : Codable {
let id : Int?
let name : String?
let symbol : String
let quotes : [String: Quotes]
}
struct Quotes : Codable {
let price : Double?
}
JSON
"data": {
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 2,
"circulating_supply": 99859856.0,
"total_supply": 99859856.0,
"max_supply": null,
"quotes": {
"USD": {
"price": 604.931,
"volume_24h": 1790070000.0,
"market_cap": 60408322833.0,
"percent_change_1h": -0.09,
"percent_change_24h": -2.07,
"percent_change_7d": 11.92
}
}
解决方案
要过滤数组并显示单个值(或者在您的情况下找到以太坊并使用价格),您可以执行以下操作:
let ethPrice = rawResponse.data.filter({ $0.value.symbol == "ETH" }).first?.price
你把它弄得太复杂了。
如果这需要是动态的,你可以把它放在一个函数中
func getPrice(symbol: String) -> Double? {
return rawResponse.data.filter({ $0.value.symbol == symbol }).first?.price
}
您需要考虑在较小的工作中正在做什么。
获取您想要的对象,即这部分
let item = rawResponse.data.filter({ $0.value.symbol == symbol }).first
然后,您可以访问该对象的所有属性。
如果您想打印所有商品的名称和价格,您也可以很容易地做到这一点
for item in rawResponse.data {
print("\(item.symbol) - \(item.price)"
}
推荐阅读
- c# - 错误:出现一个或多个错误。重定向或身份验证重播过多
- bash - 无法从 apache localhost 运行 ant(ant:找不到命令)
- laravel - Laravel Redis 密钥格式未按预期工作
- html - 如何从动态视图侧边栏的 Blogger 代码中删除菜单栏?
- excel - 拆分单元格以填充两个文本框
- css - 在样式化组件中的图像上添加文本
- reactjs - 当我只是将它的引用传递给 addEventListener 时,为什么我的函数正在执行?
- wordpress - 卸载 SES Lite - Wordpress 用户角色不显示任何内容,除非提供管理员权限
- soap - 使用 Quarkus 创建 SOAP 客户端无法导入 @CXFClient
- webspeech-api - WebSpeechAPI:SpeechSynthesisUtterance() 在几个字符后无法读取内容