VBA访问没有名称属性{j}的json属性

时间:2017-05-25 10:03:10

标签: json vba

我正在尝试从VBA访问来自JSON文件as you can see here的508“tank_id”。

我正在使用cStringBuilder,cJSONScript和JSONConverter来解析JSON文件。

我的主要问题是我无法通过扔掉所有这些ID,因为我不知道如何获得没有名字的“1”“33”“49”“81”。

这是我尝试获取它们的代码,但没有成功。

Const myurl2 As String = "https://api.worldoftanks.eu/wot/encyclopedia/vehicles/?application_id=demo&fields=tank_id"

Sub List_id_vehicules()

Dim strRequest
Dim xmlHttp: Set xmlHttp = CreateObject("msxml2.xmlhttp")
Dim response As Object
Dim rows As Integer
Dim counter As Integer
Dim j As String
Dim k As Integer: k = 2
Dim url As String

url = myurl2
xmlHttp.Open "GET", url, False
xmlHttp.setRequestHeader "Content-Type", "text/xml"
xmlHttp.send
While Not xmlHttp.Status = 200            '<---------- wait
Wend
Set response = ParseJson(xmlHttp.ResponseText)
rows = response("meta")("count")

For counter = 1 To rows
    j = counter
    Dim yop As String
    yop = "data[" & j & "][" & j & "]"
    Sheets(2).Cells(1 + counter, 1).Value = response('data[counter]')['tank_id']
Next counter

END Sub

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

JSONConverter实质上将JSON文本字符串解析为一组嵌套的Dictionary对象。因此,当ParseJson函数返回Object时,它实际上是Dictionary。然后,当您访问response("meta")时,“meta”部分是Key对象的Dictionary。这与你在JSON中嵌套是一回事。

因此,当您尝试访问response("data")("3137")时,您正在使用Dictionary访问response("data")返回的key="3137"。现在的诀窍是如何从Keys对象中获取所有response("data")

以下是一些示例代码,用于说明如何列出JSON数据部分中的所有储罐ID:

Option Explicit

Sub ListVehicleIDs()
    Const jsonFilename As String = "C:\Temp\tanks.json"

    Dim fileHandle As Integer
    Dim jsonString As String
    fileHandle = FreeFile
    Open jsonFilename For Input As #fileHandle
        jsonString = Input$(LOF(fileHandle), #fileHandle)
    Close #fileHandle

    Dim jsonObj As Object
    Set jsonObj = ParseJson(jsonString)

    Dim tankCount As Long
    tankCount = jsonObj("meta")("count")

    Dim tankIDs As Dictionary
    Set tankIDs = jsonObj("data")

    Dim tankID As Variant
    For Each tankID In tankIDs.keys
        Debug.Print "Tank ID = " & tankID
    Next tankID
End Sub