Using VBscript to access all values in JSON data Using VBscript to access all values in JSON data json json

Using VBscript to access all values in JSON data


Unlike VAT and buyInfo, prices is a Collection which can contain multiple instances (notice the difference in the JSON structure, prices is encapsulated by square brackets). Whenever you deal with Collections a loop is required to iterate through the instances to get at their underlying properties.

I'd recommend a For Each loop, like below. #

Dim key, price'Iterating a Scripting.Dictionary using For Each returns the key.For Each key In oJSON.data("prices")  'Get the price instance by passing the key back into   'the Scripting.Dictionary.  Set price = oJSON.data("prices")(key)  MsgBox price.item("unitPrice")  MsgBox price.item("specialOfferPrice")  MsgBox price.item("period").item("endDate")  MsgBox price.item("period").item("startDate")  'Clear object before iterating the next instance.  Set price = NothingNext

# Code provided untested


Looking into this a bit more with some useful discussion with @omegastripes in the comments and looking through the aspJSON class, you should be able to access the Collection / Array items by ordinal, for example to get unitPrice you would use;

oJSON("prices")(0).Item("unitPrice")

With this in mind did a quick test script and here is the result.

Option ExplicitDim prices: Set prices = CreateObject("Scripting.Dictionary")Dim price, periodWith prices    Set price = CreateObject("Scripting.Dictionary")    With price        Call .Add("unitPrice", 12.50)        Call .Add("specialOfferPrice", 8.75)        Set period = CreateObject("Scripting.Dictionary")        With period            Call .Add("endDate", "/Date(928142400000+0200)/")        End With        Call .Add("period", period)    End With    'Uses same method as the AddToCollection() in aspJSON to    'assign the ordinal position when adding the child Dictionary.    Call .Add(.Count, price)End WithWScript.Echo prices(0).Item("unitPrice")WScript.Echo prices(0).Item("period").Item("endDate")

Output:

12.5/Date(928142400000+0200)/