我正在尝试从json数组中提取信息而我收到此错误
“无法下标类型'[[String:Any]]'的值,其索引类型为'String'”
这里
if let rev = place.details?["reviews"] as? [[String:Any]] {
if let ver = rev["author_name"] as? String { // <- IN THIS LINE I GET THE ERROR
}
}
我知道如果我将类型转换为[String : Any]
而不是[[String:Any]]
它将起作用,但在这种情况下我必须将其转换为数组数组,否则它不会读取json那么我该如何解决这个问题呢?
答案 0 :(得分:3)
[[String:Any]]
是一个数组。它只能由Int
索引订阅。
您必须迭代数组,例如:
if let reviews = place.details?["reviews"] as? [[String:Any]] {
for review in reviews {
if let authorName = review["author_name"] as? String {
// do something with authorName
}
}
}
答案 1 :(得分:2)
您无法使用String
访问数组中的项目。您必须使用Int
[[String:Any]]
这是一系列词典。
答案 2 :(得分:1)
[[String:Any]]
是一个二维数组。它只能使用 Int 索引进行下标。
最好使用forEach
循环,例如
if let reviews = place.details?["reviews"] as? [[String:Any]] {
reviews?.forEach { review in
if let authorName = review["author_name"] as? String {
// do something with authorName
}
}
}
答案 3 :(得分:0)
我认为你在这里混合了字典和数组。 如果要访问数组中的元素,则必须使用像此
这样的Int
索引
let a = ["test", "some", "more"] // your array
let b = a[0] // print(b) = "test"
如果您想访问字典中的元素,可以通过其密钥访问它,例如String
let dict: [String: Any] = ["aKey": "someValue"]
let value = dict["aKey"] // print(value) = "someValue"
在您的情况下,您有一系列词典,每个词典都包含有关审阅的信息。如果您想访问其中一个评论的作者,您必须首先从您的数组中获取评论字典,如下所示:
if let reviews = place.details?["reviews"] as? [[String:Any]],
let review = reviews[0] {
// here you can access the author of the review then:
if let author = review["author_name"] as? String {
// do something
}
}
您可以通过数组循环访问所有评论,而不是仅仅访问我的示例中的第一个评论