无法使用 'String' 类型的索引下标“[[String : Any]]”类型的值

Cannot subscript a value of type '[[String : Any]]' with an index of type 'String'

我正在尝试从 json 数组中提取信息,但出现此错误

"Cannot subscript a value of type '[[String : Any]]' with an index of type '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,我该如何解决这个问题?

您无法使用 String 访问数组中的项目。你必须使用 Int

[[String:Any]]这是字典数组。

[[String:Any]] 是一个数组。只能下标Int index.

您必须遍历数组,例如:

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
        }
    }
}

[[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
        }
    }
}

我认为您在这里混淆了字典和数组。 如果你想访问数组中的元素,你必须使用这样的 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
      }
}

除了像我的示例中那样只访问第一条评论,您还可以通过数组循环逐条访问所有评论