我如何通过JSON结构迭代访问结构中的第一个日期?



这是我的JSON:

{
"col": {
"2021-02-14": [
{
"name": "green",
"size": "large",
},
{
"name": "grey",
"size": "small",
},
{
"name": "blue",
"size": "small",
}
],
"2021-02-21": [
{
"name": "grey",
"size": "large",
},
{
"name": "grey",
"size": "small",
}
]
}
}

日期,例如"2021-02-14"是一个动态键,这就是为什么我尝试使用For-In循环来访问它。我设法编写了循环遍历整个结构的代码,但随机返回日期,有时为"2021-02-14"。首先打印,有时"2021-02-14"是第一次。我知道字典是键值关联的无序集合,但有什么方法可以解决这个问题吗?我的代码如下:

func parseMyJSON() {

if let dates = try? JSON(data: data) {

let col = dates["col"]

for (key, subJson) in col {
print(key)
for (_, subJson) in subJson {
print(subJson["name"], subJson["size"], subJson["image"])

}
}
}
}

输出:

2021-02-21
grey large 
grey small 
2021-02-14
green large 
grey small 
blue small 

谢谢

  • 获取col键的字典
  • 排序键
  • 获取第一个键的值并迭代数组

if let dates = try? JSON(data: data),
let col = dates["col"].dictionary,
let firstKey = col.keys.sorted().first {
for subJson in col[firstKey]!.arrayValue {
print(subJson["name"], subJson["size"], subJson["image"])
}
}
}

旁注:由于Swift 4SwiftyJSON已经过时,支持Codable协议。

最新更新