使用Python将swagger的openapi.json文件转markdown
import json
# Load the JSON file
with open("/mnt/data/openapi.json", "r", encoding='utf-8') as file:
openapi_data = json.load(file)
# Function to convert JSON to Markdown
def convert_to_markdown(openapi_data):
markdown = f"# {openapi_data.get('info', {}).get('title', 'API Documentation')}\n\n"
markdown += f"## 版本: {openapi_data.get('info', {}).get('version', 'N/A')}\n\n"
paths = openapi_data.get("paths", {})
for path, methods in paths.items():
for method, details in methods.items():
markdown += f"### {path}\n\n"
markdown += f"- **方法**: {method.upper()}\n"
markdown += f"- **标签**: {', '.join(details.get('tags', []))}\n"
markdown += f"- **摘要**: {details.get('summary', '')}\n"
markdown += f"- **描述**: {details.get('description', '')}\n"
parameters = details.get('parameters', [])
if parameters:
markdown += "- **参数**:\n"
for param in parameters:
markdown += f" - **{param.get('name')}** ({param.get('in')}, {param.get('schema', {}).get('type', 'N/A')}, "
markdown += "required): " if param.get('required') else "optional): "
markdown += f"{param.get('description', '')}\n"
request_body = details.get('requestBody', {})
if request_body:
markdown += "- **请求体**:\n"
for content_type, schema in request_body.get('content', {}).items():
markdown += f" - **{content_type}**:\n"
markdown += f" - **字段**: 根据 `{schema.get('schema', {}).get('$ref', '')}`\n"
responses = details.get('responses', {})
if responses:
markdown += "- **响应**:\n"
for status, response in responses.items():
markdown += f" - **{status}**: {response.get('description', '')}\n"
markdown += "\n"
return markdown
# Convert the JSON to Markdown
markdown_content = convert_to_markdown(openapi_data)
# Save to a file
with open("/mnt/data/openapi.md", "w", encoding='utf-8') as file:
file.write(markdown_content)
markdown_content[:500] # Preview first 500 characters of the converted markdown content
好记性不如烂笔头!