0

I have a simple JSON array like this:

["123", "124", "321"]

The expected result should be 3. How can I count the number of elements without using regular expressions and always working with a JSON object?

I tried using the following code:

Dim jsonStr, jsonArray, elementCount
jsonStr = "[""123"", ""124"", ""321""]"
Set jsonScriptControl = CreateObject("ScriptControl")
jsonScriptControl.Language = "JScript"
Set jsonArray = jsonScriptControl.Eval("(" + jsonStr + ")")
elementCount = jsonArray.Length
MsgBox "Number of elements: " & elementCount

However, I encountered an error message:

Microsoft VBScript runtime error: An ActiveX component cannot create an object: 'ScriptControl'.
executable
  • 3,365
  • 6
  • 24
  • 52
  • This was a few days ago... [How to access JSON object returned from createObject("htmlfile") in VBS file](https://stackoverflow.com/a/76640930) – user692942 Jul 10 '23 at 13:23
  • Does this answer your question? [Decode/Encode JSON with VBScript](https://stackoverflow.com/questions/12153925/decode-encode-json-with-vbscript) – user692942 Jul 10 '23 at 13:27
  • Does this answer your question? [How to access JSON object returned from createObject("htmlfile") in VBS file](https://stackoverflow.com/questions/76640740/how-to-access-json-object-returned-from-createobjecthtmlfile-in-vbs-file) – LesFerch Jul 10 '23 at 13:33
  • If you are sure of json being an arry you can use elementCount=ubound(split(jsonstr,","))+1 – Antoni Gual Via Jul 12 '23 at 06:44
  • Follow-up would be appreciated. Did you resolve the issue some other way? – LesFerch Jul 17 '23 at 13:46

1 Answers1

0

ScriptControl is a 32 bit object. Therefore, your script must be run using a 32 bit scripting host:

c:\windows\syswow64\wscript.exe My32bitScript.vbs

Alternatively, for 64bit, use htmlfile:

jsonStr = "[""123"", ""124"", ""321""]"
Set html = wscript.CreateObject("htmlfile")
Set window = html.parentWindow
window.execScript "var json = " & jsonStr, "JScript"
Set jsonArray = window.json 
elementCount = jsonArray.Length
MsgBox "Number of elements: " & elementCount
LesFerch
  • 1,540
  • 2
  • 5
  • 21