语法请求:用于分析 JSON 字符串数组的"While"语法 (VBA)



我正在努力让我的代码通过JSON字符串(相同格式)的数组循环,直到它达到数组的末尾(即,没有字符串留下)。我需要代码通过识别某个标识符(存在于每个集合中)在下一个数组中没有额外的信息来识别它已经到达终点。所以我相信我正在寻找"而"语法,说"而这个标识符有内容"根据下面的代码继续解析JSON。我现有的代码适用于我知道长度的字符串数组-不幸的是长度是可变的,因此我需要灵活的语法来调整长度(即,"for 0 to n"每次都不起作用)。

我解析的JSON代码是这样的格式:

{"id":1,"prices":[{"name":"expressTaxi","cost":{"base":"USD4.50","fareType":
"time_plus_distance","cancelFee":"USD10.00","minimumAmt":"USD8.00","perMinute":"USD1.50",
"perDistanceUnit":"USD3.00"}}] 
''note that this could have multiple arrays embedded. That is, from the "name" key to 
''the "perDistanceUnit" key would all repeat, with different value pairs. 
''The number of "name" to "perDistanceUnit" arrays is unknown. 

在这里,我想用某种类型的while循环来增加标识符结构("I"是索引号,取决于尚未实现的"while"循环中的# of循环)。

Json("prices")(i)("name") 

所以理想的情况是:

"While Json("prices")(i)("name") has information" then proceed on....

请再次注意,一切工作时,我知道长度-只是寻找一个小的语法更新,谢谢!更新:完整代码如下:

Option Explicit
Sub getJSON()
sheetCount = 1
i = 1
urlArray = Array("URL1", “URL2”, “URL3”)
Dim MyRequest As Object: Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim MyUrls: MyUrls = urlArray
Dim k As Long
Dim Json As Object
For k = LBound(MyUrls) To UBound(MyUrls)
    With MyRequest
        .Open "GET", MyUrls(k)
        .Send
        Set Json = JsonConverter.ParseJson(.ResponseText)
       ''[where I’d like some type of While statement checking into the below line for content]
        Sheets("Sheet" & sheetCount).Cells(i, 1) = Json("prices")(i)("name")
        Sheets("Sheet" & sheetCount).Cells(i, 2) = Json("prices")(i)("cost")("base")
        i = i + 1
   End With
sheetCount = sheetCount + 1
Next
End Sub

我不太熟悉你正在使用的库,看起来它将对象(包含在{ }中的项)转换为字典对象,并将数组(包含在[ ]中的事物)转换为集合。

根据解析JSON的结构,这些对象可能是嵌套的:字典中的一个元素可以是Collection(数组)。

幸运的是,这些对象类型都有一个Count属性,你可以用它来迭代它们(字典类型也有一个"键"集合)。

循环遍历每个"price":

Dim i As Long, p As Object
For i = 1 To Json("prices").Count
    Set p = Json("prices")(i)
    Debug.Print p("name"), p("cost")("base"), p("cost")("fareType")
Next i

最新更新