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

如何在VBA字典中添加嵌套数组以生成指定API POST请求JSON体

VBA Dictionary生成带嵌套数组的JSON请求体

问题说明

需要将VBA Dictionary转换为指定格式的JSON作为API POST请求体,现有代码生成的documentIds是单个对象,而目标格式中documentIds是包含对象的数组。

现有VBA代码

Dim Body As New Dictionary

Body.Add "applicationId", "customsHub"
Body.Add "exportAsContentType", "NOT_ZIPPED_SINGLE"
Body.Add "documents", New Dictionary

With Body("documents")
    .Add "documentIds", New Dictionary
    
    With Body("documents")("documentIds")
    .Add "documentId", "491e2229-471a-4b18-907a-0e25a312e5a7"
    End With
    
End With

当前生成的JSON

{
  "applicationId": "customsHub",
  "exportAsContentType": "NOT_ZIPPED_SINGLE",
  "documents": {
    "documentIds": {
      "documentId": "491e2229-471a-4b18-907a-0e25a312e5a7"
    }
  }
}

目标JSON格式

{
  "applicationId": "customsHub",
  "exportAsContentType": "NOT_ZIPPED_SINGLE",
  "documents": 
  {
    "documentIds": 
    [
      {
        "documentId": "491e2229-471a-4b18-907a-0e25a312e5a7"
      }
    ]
  }
}

修改后的VBA代码

核心是把documentIds的载体从Dictionary换成Collection(VBA中Collection转JSON时会被解析为数组),再将单个documentId对象加入这个Collection:

Dim Body As New Dictionary
Dim docIdsCollection As New Collection
Dim singleDocItem As New Dictionary

' 添加基础请求参数
Body.Add "applicationId", "customsHub"
Body.Add "exportAsContentType", "NOT_ZIPPED_SINGLE"
Body.Add "documents", New Dictionary

' 构造单个documentId对象
singleDocItem.Add "documentId", "491e2229-471a-4b18-907a-0e25a312e5a7"
' 将对象加入Collection(转JSON后对应数组结构)
docIdsCollection.Add singleDocItem

' 把Collection赋值给documents下的documentIds字段
Body("documents").Add "documentIds", docIdsCollection

关键逻辑说明

  • VBA常用的JSON转换工具(如VBA-JSON)会将Collection解析为JSON数组,Dictionary则解析为JSON对象,这是实现嵌套数组的核心依据。
  • 通过先创建单个documentId的Dictionary,再将其加入Collection,最后绑定到documentIds字段,就能生成目标要求的数组嵌套结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:43:09