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

如何自动替换Swagger JSON中的$ref引用为components内的模型?

替换Swagger JSON中$ref引用的简便方法及Swagger配置选项

Swagger(OpenAPI规范)本身没有内置的直接替换$ref引用为完整模型的配置选项,但可以通过工具或自定义脚本实现,包括处理嵌套引用的场景,具体如下:

一、简便实现方式

1. 用现成OpenAPI工具处理

  • swagger-cli:这是常用的OpenAPI工具,能一键展开所有内部/外部$ref,包括嵌套引用。执行命令:

    swagger-cli bundle your-swagger.json --outfile bundled-swagger.json --type json
    

    执行后生成的bundled-swagger.json里所有$ref都会被替换为对应的模型定义,同时保留结构完整性。

  • json-schema-ref-parser:如果需要自定义处理逻辑,用这个Node.js库写脚本更灵活:

    const $RefParser = require('json-schema-ref-parser');
    const fs = require('fs');
    
    async function dereferenceSwagger() {
      // 解析并展开所有引用
      const schema = await $RefParser.dereference('your-swagger.json');
      // 按需删除原components节点(如果不需要保留复用定义)
      delete schema.components;
      // 写入格式化后的文件
      fs.writeFileSync('dereferenced-swagger.json', JSON.stringify(schema, null, 2));
    }
    
    dereferenceSwagger();
    

2. 自定义递归脚本

如果不想依赖第三方库,可以自己写递归函数遍历JSON对象:

  • 遍历所有键值对,遇到值为包含$ref的对象时,提取#/components/schemas/xxx中的模型名称;
  • 从components/schemas中取出对应模型,替换当前$ref节点;
  • 对替换后的模型内部再次执行递归遍历,处理嵌套的$ref。

二、Swagger自身配置说明

OpenAPI规范的设计初衷就是用$ref实现模型复用,减少冗余,因此官方没有提供直接展开$ref的配置项。不过Swagger UI、Swagger Editor这类展示工具会自动解析$ref并渲染完整模型,但不会修改原始JSON文件。

示例对比

替换前:

"schema": {
  "$ref": "#/components/schemas/ModelName"
}

替换后(工具处理结果):

"schema": {
  "type": "object",
  "properties": {
    "type": {
      "type": "string",
      "nullable": true
    },
    "title": {
      "type": "string",
      "nullable": true
    },
    "status": {
      "type": "integer",
      "format": "int32",
      "nullable": true
    },
    "detail": {
      "type": "string",
      "nullable": true
    },
    "instance": {
      "type": "string",
      "nullable": true
    }
  },
  "additionalProperties": {}
}

(注:工具处理后直接展开模型内容,不会保留ModelName作为键,和你提供的示例结构略有差异,但核心是完成了引用替换)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:25:56