首先,我不再使用自定义JSON解析库,而是使用ScriptControl的Eval方法作为所有JSON代码的基础。另外,我们对本机Microsoft解决方案表示偏爱。
这是一个先前的问题,在Windows上的Excel VBA中,如何减轻IDE的大写行为破坏解析的JSON的点语法遍历的问题?这个问题基于此。它显示了与使用点语法遍历已解析的JSON对象相比,使用VBA.CallByName的鲁棒性更高。
在此问题中,询问如何遍历已解析的JSON数组。首先,这里是一个带帽子技巧的小脚本方法,用于ozmike
'Tools->References-> 'Microsoft Script Control 1.0; {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:\Windows\SysWOW64\msscript.ocx Private Sub TestJSONParsingArrayWithMiniScript() 'Hat tip to ozmike https://stackoverflow.com/users/334106/ozmike 'Based on https://stackoverflow.com/questions/5773683/excel-vba-parsed-json-object-loop#19359035 Dim oScriptEngine As ScriptControl Set oScriptEngine = New ScriptControl oScriptEngine.Language = "JScript" oScriptEngine.AddCode "Object.prototype.myitem=function( i ) { return this[i] } ; " Dim sJsonString As String sJsonString = "[ 1234, 2345 ]" Dim objJSON As Object Set objJSON = oScriptEngine.Eval("(" + sJsonString + ")") Debug.Assert objJSON.myitem(0) = 1234 Debug.Assert objJSON.myitem(1) = 2345 End Sub
但是,不管您相信与否,VBA.CallByName都可以本地使用,不仅可以获取数组的长度,还可以访问元素。查看答案。
因此,VBA.CallByName也可以访问数组中的元素以及找到数组的长度
'Tools->References-> 'Microsoft Script Control 1.0; {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:\Windows\SysWOW64\msscript.ocx Private Sub TestJSONParsingArrayWithCallByName() Dim oScriptEngine As ScriptControl Set oScriptEngine = New ScriptControl oScriptEngine.Language = "JScript" Dim sJsonString As String sJsonString = "[ 1234, 2345 ]" Dim objJSON As Object Set objJSON = oScriptEngine.Eval("(" + sJsonString + ")") '* Using VBA.CallByName we get the length of the array Dim lLength As Long lLength = VBA.CallByName(objJSON, "length", VbGet) Debug.Assert lLength = 2 '* Believe or not one uses "0","1",.... with callbyname to get an element Debug.Assert VBA.CallByName(objJSON, "0", VbGet) = 1234 Debug.Assert VBA.CallByName(objJSON, "1", VbGet) = 2345 End Sub