微信扫码
添加专属顾问
我要投稿
在我们日常处理大模型的输出时,经常希望输出的结果为结构化的(例如输出json格式),这样有助于我们进行结果的后处理。但是在模型输出超过限制和流式输出时就会遇到问题了,由于答案没完全输出,转json就存在问题。
效果展示
text = '''{"name":"张三", "age":'''print(parse_json_markdown(text))# {'name': '张三'}
markdown格式
text = '''```json\n{"name":"张三", "age":27'''print(parse_json_markdown(text))# {'name': '张三', 'age': 27}
多维嵌套
text = '''```json\n{"name":"张三", "age": 27, "爱好": ["羽毛球'''print(parse_json_markdown(text))# {'name': '张三', 'age': 27, '爱好': ['羽毛球']}
核心代码介绍
核心处理代码如下:
new_chars = []stack = []is_inside_string = Falseescaped = False# Process each character in the string one at a time.for char in s:if is_inside_string:if char == '"' and not escaped:is_inside_string = Falseelif char == "\n" and not escaped:char = "\\n"# Replace the newline character with the escape sequence.elif char == "\\":escaped = not escapedelse:escaped = Falseelse:if char == '"':is_inside_string = Trueescaped = Falseelif char == "{":stack.append("}")elif char == "[":stack.append("]")elif char == "}" or char == "]":if stack and stack[-1] == char:stack.pop()else:# Mismatched closing character; the input is malformed.return None
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2025-12-19
谷歌发布Gemini 3 Flash,全球免费,打破速度与智能不可兼得悖论
2025-12-19
刚刚,OpenAI最强编程大模型发布!
2025-12-19
AI架构师的诞生:AI+传统DDD模式 = 实现开发效率提升75%
2025-12-19
Anthropic 指路,Letta 破局:Agent 下半场的关键词是 Skills
2025-12-19
突发|ChatGPT 版应用商店正式上线
2025-12-18
端侧AI革命!Android App上可直接集成Gemini大模型了!
2025-12-18
突发!ChatGPT版应用商店正式发布,第三方开发者新入口!
2025-12-18
实测豆包1.8后,我终于明白字节为什么要推豆包手机了。
2025-10-26
2025-10-02
2025-09-29
2025-10-07
2025-09-30
2025-11-19
2025-10-20
2025-11-13
2025-10-02
2025-10-18
2025-12-16
2025-12-15
2025-12-14
2025-12-12
2025-12-12
2025-12-11
2025-12-09
2025-12-08