微信扫码
添加专属顾问
我要投稿
在我们日常处理大模型的输出时,经常希望输出的结果为结构化的(例如输出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+中大型企业
2026-03-20
Cursor自研模型反超Opus 4.6!价格脚踝斩,氛围编程沸腾了
2026-03-20
突发!Claude Code 要彻底龙虾化
2026-03-20
1 个文件让 Claude Code 记住你:MEMORY.md 全解析
2026-03-20
为了狠狠嫖Google Antigravity 24 小时,我竟然做这个....
2026-03-19
GPT-5.4 mini 与 GPT-5.4 nano 登陆 Microsoft Foundry (国际版)
2026-03-19
AI的边界,就是人类的领地
2026-03-19
百度这件事我跟别人解释了好多次
2026-03-19
马化腾说的养虾,不只是养虾
2026-01-24
2026-01-10
2026-01-01
2026-01-26
2025-12-21
2026-01-09
2026-01-09
2025-12-30
2026-01-23
2026-01-14
2026-03-19
2026-03-19
2026-03-19
2026-03-18
2026-03-17
2026-03-17
2026-03-09
2026-03-08