You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA Access解析Google Books JSON嵌套作者数组问题

解决VBA Access处理Google Books JSON可变作者数组的问题

示例JSON响应片段

{
  "items": [
    {
      "volumeInfo": {
        "title": "示例书籍",
        "authors": ["张三", "李四", "王五"],
        "publisher": "示例出版社"
      }
    }
  ]
}

问题核心

硬编码取前3位作者的方式会因数组长度不足触发越界错误,正确做法是动态遍历作者数组,收集所有作者名后合并为字符串,适配任意数量的作者。

修改后的VBA代码

Sub GetGoogleBooksAuthors()
    Dim jsonText As String
    Dim jsonObj As Object
    Dim volumeInfo As Object
    Dim authorsColl As Collection
    Dim authorsStr As String
    Dim i As Integer
    
    ' 替换为你的Google Books API返回的JSON字符串
    ' jsonText = [API请求返回的JSON内容]
    
    ' 解析JSON对象
    Set jsonObj = JsonConverter.ParseJson(jsonText)
    
    ' 获取第一本图书的volumeInfo(多本图书需遍历items数组)
    Set volumeInfo = jsonObj("items")(1)("volumeInfo")
    
    ' 处理作者数组
    authorsStr = ""
    If volumeInfo.Exists("authors") Then
        Set authorsColl = volumeInfo("authors")
        ' 方式1:直接遍历拼接字符串
        For i = 1 To authorsColl.Count
            If authorsStr <> "" Then authorsStr = authorsStr & ", "
            authorsStr = authorsStr & authorsColl(i)
        Next i
        
        ' 方式2:转原生数组后用Join(更简洁)
        ' Dim tempArr() As String
        ' ReDim tempArr(1 To authorsColl.Count)
        ' For i = 1 To authorsColl.Count
        '     tempArr(i) = authorsColl(i)
        ' Next i
        ' authorsStr = Join(tempArr, ", ")
    Else
        authorsStr = "无作者信息"
    End If
    
    ' 赋值到TextBox
    Me.txtAuthors.Value = authorsStr
End Sub

关键说明

  1. 判断数组存在性:用volumeInfo.Exists("authors")避免因无作者字段触发错误
  2. 处理VBA-JSON的Collection:解析后的作者数组是Collection对象,不是原生数组,需遍历转换后才能用Join;直接拼接字符串则无需转换
  3. 动态适配长度:通过authorsColl.Count获取实际作者数量,遍历次数随数组长度变化,不会出现越界问题

额外提示

如果返回结果包含多本图书,需要在外层增加对jsonObj("items")的遍历循环,逐个处理每本图书的作者信息。

内容的提问来源于stack exchange,提问作者Bookworm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:35:29