我有这样的JSON:
{
"SKzSjdBuOpO49wkPVaxtmLQoR0O2": {
location: "-LB1fn5GQKTaIc-fGNPS"
},
"s0ntSZP7mBQw1a8ua0E5PqazlqJ2": {
location: "-LB23izD7bp2NhO0UuIo"
},
"FEScjelpNSR7vuVz1ha6Z6uSfF43": {
location: "-LB1JLABuJO1NyJ-v2t_"
},
"mW7dGja6cRRB0d9uSIhg4f35PzC3": {
location: "-LB5xqUvIjEgtW_FH_nG"
},
"GCnt0VKcqjT8bl2chw43nsntaZK2": {
location: "-LB1n8ga9C0vCcZXD2Us"
}
}
在我的Values[String: Any]
字典中。我想从其值创建另一个字典来访问位置值。
你能帮我这么做吗?
答案 0 :(得分:0)
尽量不要在swift中使用Dictionary
,而在您的情况下,您可以使用[String : [String: String]]
类型,然后遍历您的数据以获取所需的值。试试这个
let dict = ["SKzSjdBuOpO49wkPVaxtmLQoR0O2": [
"location" : "-LB1fn5GQKTaIc-fGNPS",
], "s0ntSZP7mBQw1a8ua0E5PqazlqJ2": [
"location" : "-LB23izD7bp2NhO0UuIo",
], "FEScjelpNSR7vuVz1ha6Z6uSfF43": [
"location" : "-LB1JLABuJO1NyJ-v2t_",
], "mW7dGja6cRRB0d9uSIhg4f35PzC3": [
"location" : "-LB5xqUvIjEgtW_FH_nG",
], "GCnt0VKcqjT8bl2chw43nsntaZK2": [
"location" : "-LB1n8ga9C0vCcZXD2Us",
]]
var newDict = [String: String]()
for (key, val) in dict {
newDict[key] = val["location"]
}
print(newDict)
输出:
[“SKzSjdBuOpO49wkPVaxtmLQoR0O2”:“ - LB1fn5GQKTaIc-fGNPS”, “s0ntSZP7mBQw1a8ua0E5PqazlqJ2”:“ - LB23izD7bp2NhO0UuIo”, “FEScjelpNSR7vuVz1ha6Z6uSfF43”:“ - LB1JLABuJO1NyJ-v2t_”, “mW7dGja6cRRB0d9uSIhg4f35PzC3”:“ - LB5xqUvIjEgtW_FH_nG”, “GCnt0VKcqjT8bl2chw43nsntaZK2”:“ - LB1n8ga9C0vCcZXD2Us”]
对于你的情况,因为你有字典,你可以试试这个:
let dict = ["SKzSjdBuOpO49wkPVaxtmLQoR0O2": [
"location" : "-LB1fn5GQKTaIc-fGNPS",
], "s0ntSZP7mBQw1a8ua0E5PqazlqJ2": [
"location" : "-LB23izD7bp2NhO0UuIo",
], "FEScjelpNSR7vuVz1ha6Z6uSfF43": [
"location" : "-LB1JLABuJO1NyJ-v2t_",
], "mW7dGja6cRRB0d9uSIhg4f35PzC3": [
"location" : "-LB5xqUvIjEgtW_FH_nG",
], "GCnt0VKcqjT8bl2chw43nsntaZK2": [
"location" : "-LB1n8ga9C0vCcZXD2Us",
]] as Dictionary<String, Any>
var newDict = [String: String]()
for (key, val) in dict {
if let value = val as? [String: String] {
newDict[key] = value["location"]
}
}
print(newDict)
答案 1 :(得分:0)
如果主要目标只是访问值并且类型固定为[String: Any]
,请执行以下操作:
if let info = dictionary["SKzSjdBuOpO49wkPVaxtmLQoR0O2"] as? [String : String] {
let location = info["location"]
}