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

如何在Python中提取去除Markdown代码块包裹的纯JSON对象?

提取Markdown代码块中的纯JSON对象(Python实现)

问题描述

调用chat_completion接口后返回的结果包含Markdown代码块标记(以```json开头,```结尾),需要在Python中提取其中的纯JSON内容,去除这些标记。现有代码仅处理了"json"前缀,未覆盖完整的代码块标记场景。

解决方案

方法1:固定格式字符串切片(简单快速)

如果返回结果的代码块格式严格固定(开头必为```json,结尾必为```),可以直接通过字符串定位和切片提取:

def extract_json_from_markdown(result):
    cleaned_result = result.strip()
    start_marker = "```json"
    end_marker = "```"
    
    if cleaned_result.startswith(start_marker) and cleaned_result.endswith(end_marker):
        # 截取标记之间的内容并去除首尾空白
        json_str = cleaned_result[len(start_marker):-len(end_marker)].strip()
        return json_str
    # 格式不符时返回原内容(可根据需求改为抛出异常)
    return cleaned_result

更新原调用代码的处理逻辑:

for fragment_string in fragment_strings:
    prompt = generate_prompt(fragment_string)
    messages = [{"role": "user", "content": prompt}]
    result = chat_completion(messages)
    
    # 提取纯JSON
    json_str = extract_json_from_markdown(result)
    
    print(f'{json_str} \n')

方法2:正则表达式匹配(兼容格式变化)

如果代码块标记存在空格、换行等格式变动,正则表达式能更灵活地匹配提取:

import re

def extract_json_from_markdown(result):
    # 匹配```json开头、```结尾的内容,支持中间包含换行符
    pattern = r'```json\s*(.*?)\s*```'
    match = re.search(pattern, result, re.DOTALL)
    if match:
        return match.group(1).strip()
    # 匹配失败时返回原内容
    return result.strip()

方法3:Markdown解析库(处理复杂场景)

如果需要处理包含多个代码块的复杂Markdown内容,可使用专业库解析:

  1. 先安装依赖库:
pip install markdown beautifulsoup4
  1. 实现提取逻辑:
from markdown import markdown
from bs4 import BeautifulSoup

def extract_json_from_markdown(result):
    # 将Markdown转换为HTML结构
    html_content = markdown(result)
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 遍历所有代码块,筛选出JSON类型的块
    for code_block in soup.find_all('code'):
        if 'language-json' in code_block.get('class', []):
            return code_block.get_text().strip()
    # 未找到JSON代码块时返回原内容
    return result.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:36:02