markdown_utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. Markdown工具类
  3. 提供处理markdown格式内容的工具函数。
  4. """
  5. import json
  6. from typing import Any, Dict, Optional
  7. def parse_markdown_json(content: str) -> Optional[Dict[str, Any]]:
  8. """
  9. 解析markdown格式的JSON内容
  10. 从markdown格式的字符串中提取并解析JSON内容,去除 ```json 和 ``` 标签。
  11. Args:
  12. content: 包含markdown格式JSON的字符串
  13. Returns:
  14. 解析后的JSON字典,如果解析失败返回None
  15. """
  16. if not content:
  17. return None
  18. # 去除首尾空白
  19. stripped_content = content.strip()
  20. # 检查是否以 ```json 开头并以 ``` 结尾
  21. if stripped_content.startswith("```json") and stripped_content.endswith("```"):
  22. # 提取 ```json 和 ``` 之间的内容
  23. json_content = stripped_content.replace("```json", "", 1)
  24. json_content = json_content.rstrip("```").strip()
  25. try:
  26. # 解析为JSON
  27. return json.loads(json_content)
  28. except json.JSONDecodeError:
  29. # 解析失败
  30. return None
  31. return None
  32. def extract_json_from_markdown(content: str) -> str:
  33. """
  34. 从markdown字符串中提取JSON内容
  35. 去除 ```json 和 ``` 标签,返回纯JSON字符串。
  36. Args:
  37. content: 包含markdown格式JSON的字符串
  38. Returns:
  39. 纯JSON字符串,如果没有找到JSON标签返回原始内容
  40. """
  41. if not content:
  42. return content
  43. # 去除首尾空白
  44. stripped_content = content.strip()
  45. # 检查是否以 ```json 开头并以 ``` 结尾
  46. if stripped_content.startswith("```json") and stripped_content.endswith("```"):
  47. # 提取 ```json 和 ``` 之间的内容
  48. json_content = stripped_content.replace("```json", "", 1)
  49. json_content = json_content.rstrip("```").strip()
  50. return json_content
  51. return content