微信扫码
添加专属顾问
我要投稿
在我们日常处理大模型的输出时,经常希望输出的结果为结构化的(例如输出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 = False
escaped = 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 = False
elif char == "\n" and not escaped:
char = "\\n"# Replace the newline character with the escape sequence.
elif char == "\\":
escaped = not escaped
else:
escaped = False
else:
if char == '"':
is_inside_string = True
escaped = False
elif 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-09-07
蚂蚁即将上线通用 Agent
2025-09-07
跃过互联网,AI Agent 正构建全新通信方式 | LinkedIn联合创始人万字对话实录
2025-09-07
为什么我愿意为AI会议记录付费?——从Granola看产品开发的两种哲学
2025-09-07
万字长文|AI智能体与模型进化:如何在企业落地中平衡创新与风险
2025-09-07
Sam为何认为GPT将催生千亿美元“独角兽个人公司”
2025-09-07
大参林亿级Elasticsearch搜索性能调优实践
2025-09-07
前端效能大突破:cursor引领企业前端开发新革命!
2025-09-07
揭秘AI语音识别:从AI语音服务搭建到K8s容器化部署
2025-08-21
2025-06-21
2025-08-21
2025-08-19
2025-06-12
2025-06-19
2025-06-13
2025-07-29
2025-06-15
2025-08-19
2025-09-07
2025-09-06
2025-09-03
2025-09-03
2025-09-03
2025-09-03
2025-09-02
2025-08-28