You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MS Access中VBA解析JSON嵌套数组提取指定属性集数据遇阻

问题描述

我用VBA在MS Access中调用API,已成功获取Items集合的数据,但无法提取SetName为DG的AttributeSet下的Attributes集合数据(返回结果中可能存在多个AttributeSet)。参考同类技术帖后仍未解决,附上相关信息请求技术帮助:


附相关信息

返回的JSON数据示例

{
  "Items": [
    {
      "Id": "ITEM001",
      "AttributeSet": [
        {
          "SetName": "DG",
          "Attributes": [
            {"Key": "Size", "Value": "L"},
            {"Key": "Color", "Value": "Blue"}
          ]
        },
        {
          "SetName": "Basic",
          "Attributes": [
            {"Key": "SKU", "Value": "SKU001"}
          ]
        }
      ]
    }
  ]
}

我的VBA代码片段

' API请求部分(正常工作)
Dim http As Object
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "你的API地址", False
http.Send

' JSON解析部分
Dim jsonObj As Object
Set jsonObj = JsonConverter.ParseJson(http.ResponseText)

' 获取Items集合正常
Dim items As Object
Set items = jsonObj("Items")

' 尝试提取DG的Attributes(此处失败)
Dim targetAttrs As Object
' 原错误尝试代码:
' Set targetAttrs = items(1)("AttributeSet")("DG")("Attributes")

本地窗口截图说明

本地窗口显示Items集合数据完整,但直接通过键名访问AttributeSet的目标项时,提示「对象不支持该属性或方法」;遍历AttributeSet时,无法正确读取SetName属性值。


解决方法

1. 遍历AttributeSet集合匹配目标SetName

JSON中的AttributeSet是数组类型,不能直接通过SetName作为键访问,必须循环遍历匹配:

Dim item As Object
Dim attrSets As Object
Dim attrSet As Object
Dim targetAttributes As Object

' 遍历每个Item
For Each item In items
    Set attrSets = item("AttributeSet")
    ' 遍历每个AttributeSet
    For Each attrSet In attrSets
        ' 匹配SetName为DG的项
        If attrSet("SetName") = "DG" Then
            Set targetAttributes = attrSet("Attributes")
            ' 处理Attributes数据(示例:输出到立即窗口)
            Dim attr As Object
            For Each attr In targetAttributes
                Debug.Print attr("Key") & ": " & attr("Value")
            Next attr
            Exit For ' 找到目标后退出循环,若存在多个DG集合可移除该行
        End If
    Next attrSet
Next item

2. 检查JSON键名与代码的匹配度

JSON是大小写敏感的,需确认:

  • 代码中引用的键名(如"AttributeSet"、"SetName")与返回JSON的键名完全一致
  • AttributeSet是数组而非单个对象,需用For Each遍历而非直接索引

3. 调试中间对象确认结构

在代码中加入调试语句,查看AttributeSet的实际结构:

For Each attrSet In attrSets
    Debug.Print "当前SetName:" & attrSet("SetName")
    Debug.Print "Attributes数量:" & attrSet("Attributes").Count
Next attrSet

通过立即窗口输出的信息,确认是否能正常读取SetName和Attributes属性。

内容的提问来源于stack exchange,提问作者dbblmb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:25:47