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

如何编写可动态同步含JSON的Python文件变更的Markdown接口控制文档?

动态同步JSON Schema到Markdown接口文档的实现方案

1. 从Python文件提取JSON Schema

先通过脚本解析Python文件,把目标JSON结构提取出来,以example_file_with_json.py里的properties字段为例:

import json
import re

def extract_schema(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    # 匹配properties对应的JSON代码块(可根据实际代码结构调整正则)
    schema_match = re.search(r'"properties":\s*({.*?})', content, re.DOTALL)
    if schema_match:
        return json.loads(schema_match.group(1))
    return {}

# 获取解析后的schema
schema_data = extract_schema('example_file_with_json.py')
wheel_size_type = schema_data.get('wheelSize', {}).get('type', 'unknown')

2. 生成动态Markdown文档

用模板引擎(如Jinja2)渲染Markdown,把提取到的类型变量插入到指定位置:

第一步:创建Markdown模板

新建api_doc_template.md,在需要动态替换的位置用变量占位:

# 接口参数规范
- **wheelSize**:请确保wheelSize使用{{ wheel_size_type }}数据类型

第二步:渲染生成最终文档

用脚本加载模板并填充变量:

from jinja2 import Template

def generate_doc(schema, template_path, output_path):
    with open(template_path, 'r', encoding='utf-8') as f:
        template = Template(f.read())
    # 提取字段类型
    wheel_type = schema.get('wheelSize', {}).get('type', 'unknown')
    # 渲染并写入文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(template.render(wheel_size_type=wheel_type))

# 生成最终文档
generate_doc(schema_data, 'api_doc_template.md', 'api_spec.md')

3. 实现自动同步

把上述脚本集成到自动化流程里,确保JSON变更时文档自动更新:

  • 用Git的pre-commit钩子:每次提交Python文件前,自动执行脚本更新Markdown文档
  • 用CI/CD工具:比如仓库代码变更时,自动触发脚本更新文档并提交

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:40:28