访问VBA中JSON对象中的嵌套值
我想从一个JSON对象(我从RESTAPI获得)获取数据,并使用VBA将一些数据显示到Excel工作表中。我正在使用这个库(VBA-JSON v2.3.1 JsonConverter) 我有以下JSON对象:访问VBA中JSON对象中的嵌套值,json,excel,vba,nested,Json,Excel,Vba,Nested,我想从一个JSON对象(我从RESTAPI获得)获取数据,并使用VBA将一些数据显示到Excel工作表中。我正在使用这个库(VBA-JSON v2.3.1 JsonConverter) 我有以下JSON对象: { "devices": [ { "data": [ { "id": 0, "name": "Hello"
{
"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看起来像下面的对象,那么我的代码就可以工作了。但我的问题是,我得到的响应更加嵌套,我无法直接访问“数据”
我只是不知道,如何访问JSON对象中更深层次的值。使用print的类似问题的解决方案不适用于我的代码
谢谢你帮助我 您的“root”json对象是一个字典-键“devices”是一个集合对象,第一个元素是另一个字典,其中有两个键“data”和“type”
“数据”是另一个字典集合,因此您可以这样做以获取包含的id
和name
值:
Dim Json作为对象、数据、d
'正在从工作表单元格读取json。。。
设置Json=JsonConverter.ParseJson(范围(“A5”).Value)
设置data=Json(“设备”)(1)(“数据”)“字典键->集合索引->字典键
对于数据中的每个d
调试。打印d(“id”)、d(“名称”)
下一个d
输出:
0你好
你好吗?
再见
您好,非常感谢您的回答!代码正在运行!
{
"devices": [
{
"id": 0,
"name": "Hello"
},
{
"id": 1,
"name": "How are you?"
},
{
"id": 2,
"name": "Bye"
}
]
}