VBA中用JsonParse解析JSON后,如何访问数组子结构并统计数量?
VBA解析JSON数组:统计书籍数量并遍历标题
你使用的JsonParse函数是通过JScript引擎解析JSON,返回的是JScript环境中的对象,并非VBA原生数组,因此不能直接用VBA的UBound()或book[0]这类语法,需采用JScript对象的属性与调用方式处理数组结构。
正确访问数组的语法
- 获取书籍总数:调用JScript数组的
length属性,格式为jsonObject.book.length - 遍历数组元素:在VBA中通过圆括号索引访问数组元素,例如
jsonObject.book(i).title(i为循环变量,从0开始计数)
完整示例代码
Sub ProcessBooksJson() Dim jsonStr As String Dim jsonObject As Object Dim bookCount As Integer Dim i As Integer ' 示例JSON字符串 jsonStr = "{""person"": {""name"": ""Bob"",""age"": 30,""address"": {""city"": ""New York"",""zip"": 10001}},""book"": [{""title"": ""The Catcher in the Rye"",""author"": ""J.D. Salinger"",""price"": 19.99},{""title"": ""The Lord of the Rings"",""author"": ""J.R.R. Tolkien"",""price"": 29.99},{""title"": ""Harry Potter and the Philosopher's Stone"",""author"": ""J.K. Rowling"",""price"": 14.99}]}" ' 解析JSON Set jsonObject = JsonParse(jsonStr) ' 获取书籍数量 bookCount = jsonObject.book.length Debug.Print "书籍总数:" & bookCount ' 遍历输出每本书的标题 Debug.Print "书籍列表:" For i = 0 To bookCount - 1 Debug.Print "第" & i + 1 & "本:" & jsonObject.book(i).title Next i Set jsonObject = Nothing End Sub ' 你的JsonParse函数 Public Function JsonParse(jsonStr As String) As Object With CreateObject("HTMLFile") Set Window = .parentWindow Window.execScript "var json = " & jsonStr, "JScript" Set JsonParse = Window.json End With End Function
关键说明
- 不要使用VBA数组的
UBound()函数,JScript数组的长度需通过length属性获取 - VBA中调用JScript数组索引时,必须用圆括号
(),而非JavaScript语法的方括号[] - JScript数组索引从0开始,遍历范围需设置为
0到length-1
内容的提问来源于stack exchange,提问作者刘东辰
相关产品推荐
相关产品推荐

