我想从一个 JSON 对象中获取数据,我从一个 Rest-API 中获取数据,并使用 VBA 将一些数据显示到 Excel 工作表中。我正在使用该库(VBA-JSON v2.3.1 JsonConverter)。
我有以下 JSON 对象:
{
"devices": [
{
"data": [
{
"id": 0,
"name": "Hello"
},
{
"id": 1,
"name": "How are you?"
},
{
"id": 2,
"name": "Bye"
}
],
"type": "LORA"
}
],
"includedTypes": [
"LORA"
]
}
我想从“数据”中获取数组中的对象。我的 VBA 代码是这样的:
Dim js1Object As Object
Dim response1 As String
strUrl = "https://XXXXXXXXXXXdevices
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.SetRequestHeader "Authorization", "Bearer " & apitoken
.Send
response1 = hReq.responseText
MsgBox response1
Set js1Object = JsonConverter.ParseJson(response1)
j = 31
For Each item In js1Object("devices")
ws.Cells(j, 7) = item("id")
ws.Cells(j, 10) = item("name")
j = j + 1
Next
MsgBox (response1)
End With
如何访问“数据”中的值?如果 JSON 看起来像下面的对象,我的代码就可以工作。但我的问题是,我得到的响应更加嵌套,我无法直接访问“数据”。
{
"devices": [
{
"id": 0,
"name": "Hello"
},
{
"id": 1,
"name": "How are you?"
},
{
"id": 2,
"name": "Bye"
}
]
}
我只是不知道如何在 JSON-Object 中访问更深层次的值。来自类似打印问题的解决方案不适用于我的代码。谢谢你帮助我!
最佳答案
您的“根”json 对象是一个字典 - 键“设备”是一个集合对象,第一个元素是另一个具有两个键“数据”和“类型”的字典。
“数据”是另一个字典集合,因此您可以这样做以获取包含的 id
和 name
值(value)观:
Dim Json As Object, data, d
'reading json from a worksheet cell...
Set Json = JsonConverter.ParseJson(Range("A5").Value)
Set data = Json("devices")(1)("data") 'Dictionary key->Collection index->Dictionary key
For Each d In data
Debug.Print d("id"), d("name")
Next d
输出: 0 Hello
1 How are you?
2 Bye
关于json - 在 VBA 中访问 JSON-Object 中的嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66092311/