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

如何使用OpenAPI 3为动态键名的响应对象结构编写文档

你给出的JSON属于键为动态字符串、值为固定结构对象的字典(映射)结构,在OpenAPI 3中可以通过additionalProperties关键字定义这类动态key的结构,具体写法如下:

核心Schema定义

components:
  schemas:
    # 内层固定结构的子对象定义
    Item:
      type: object
      properties:
        prop1:
          type: integer
          example: 1
        prop2:
          type: integer
          example: 2
        prop3:
          type: integer
          example: 3
      required:
        - prop1
        - prop2
        - prop3

    # 外层响应结构:动态key映射
    ItemMapResponse:
      type: object
      # 所有未知key的值都符合Item结构
      additionalProperties:
        $ref: '#/components/schemas/Item'
      # 可选配置:限制key必须为数字字符串,不需要可以删除
      patternProperties:
        '^\d+$':
          $ref: '#/components/schemas/Item'

接口响应引用示例

paths:
  /your/interface/path:
    get:
      responses:
        '200':
          description: 成功返回映射集合
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ItemMapResponse'
              # 响应示例和你给出的结构完全匹配
              example:
                "1":
                  prop1: 1
                  prop2: 2
                  prop3: 3
                "2":
                  prop1: 1
                  prop2: 2
                  prop3: 3
                "3":
                  prop1: 1
                  prop2: 2
                  prop3: 3
                "4":
                  prop1: 1
                  prop2: 2
                  prop3: 3

补充说明

  • 若不需要限制动态key的格式,仅保留additionalProperties配置即可,patternProperties为可选配置,用于约束动态key的命名规则
  • 若你的动态key是固定范围的枚举值,可以单独把每个key列在properties配置中;如果是不固定数量的动态key,用additionalProperties是OpenAPI 3的标准实现方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:36:04