| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- """
- Markdown工具类
- 提供处理markdown格式内容的工具函数。
- """
- import json
- from typing import Any, Dict, Optional
- def parse_markdown_json(content: str) -> Optional[Dict[str, Any]]:
- """
- 解析markdown格式的JSON内容
-
- 从markdown格式的字符串中提取并解析JSON内容,去除 ```json 和 ``` 标签。
-
- Args:
- content: 包含markdown格式JSON的字符串
-
- Returns:
- 解析后的JSON字典,如果解析失败返回None
- """
- if not content:
- return None
-
- # 去除首尾空白
- stripped_content = content.strip()
-
- # 检查是否以 ```json 开头并以 ``` 结尾
- if stripped_content.startswith("```json") and stripped_content.endswith("```"):
- # 提取 ```json 和 ``` 之间的内容
- json_content = stripped_content.replace("```json", "", 1)
- json_content = json_content.rstrip("```").strip()
-
- try:
- # 解析为JSON
- return json.loads(json_content)
- except json.JSONDecodeError:
- # 解析失败
- return None
-
- return None
- def extract_json_from_markdown(content: str) -> str:
- """
- 从markdown字符串中提取JSON内容
-
- 去除 ```json 和 ``` 标签,返回纯JSON字符串。
-
- Args:
- content: 包含markdown格式JSON的字符串
-
- Returns:
- 纯JSON字符串,如果没有找到JSON标签返回原始内容
- """
- if not content:
- return content
-
- # 去除首尾空白
- stripped_content = content.strip()
-
- # 检查是否以 ```json 开头并以 ``` 结尾
- if stripped_content.startswith("```json") and stripped_content.endswith("```"):
- # 提取 ```json 和 ``` 之间的内容
- json_content = stripped_content.replace("```json", "", 1)
- json_content = json_content.rstrip("```").strip()
- return json_content
-
- return content
|