在这里回答我自己的问题 我已经在Excel VBA中使用JSON做了一些工作,并发布了大量的发现,我将在Q&格式 https://stackoverflow.com/help/self-answer http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/
所以在stackoverflow的其他地方,人们可以看到有关在VBA中解析JSON的问题但他们似乎错过了一两招。
首先,我不再使用自定义JSON解析库,而是使用ScriptControl的Eval方法作为我所有JSON代码的基础。 此外,我们还表达了对本机Microsoft解决方案的偏好。
以下是此问题构建的先前问题In Excel VBA on Windows, how to mitigate issue of dot syntax traversal of parsed JSON broken by IDE's capitalisation behaviour?。它显示了如何使用VBA.CallByName更健壮 而不是使用点语法来遍历解析的JSON对象。
在这个问题中,询问如何遍历解析的JSON数组。首先,这是一个miniscript方法 戴着帽子小贴士向ozmike https://stackoverflow.com/users/334106/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可以原生使用,不仅可以获得数组的长度,还可以访问元素。见答案。
这是5系列的问题2.这是完整的系列
Q2 In Excel VBA on Windows, how to loop through a JSON array parsed?
Q5 In Excel VBA on Windows, for parsed JSON variables what is this JScriptTypeInfo anyway?
答案 0 :(得分:0)
所以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