微信扫码
添加专属顾问
我要投稿
在我们日常处理大模型的输出时,经常希望输出的结果为结构化的(例如输出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-04-30
通俗易懂的梳理MCP的工作流程(以高德地图MCP为例)
2025-04-30
一文说明 Function Calling、MCP、A2A 的区别!
2025-04-30
MCP很好,但它不是万灵药|一文读懂 MCP
2025-04-30
旅行规划太难做?5 分钟构建智能Agent,集成地图 MCP Server
2025-04-29
10万元跑满血版DeepSeek,这家公司掀了一体机市场的桌子|甲子光年
2025-04-29
谷歌大神首次揭秘Gemini预训练秘密:52页PPT干货,推理成本成最重要因素
2025-04-29
一文说清:什么是算法备案、大模型备案、大模型登记 2.0
2025-04-29
MCP:AI时代的“万能插座”,大厂竞逐的焦点
2024-08-13
2024-06-13
2024-08-21
2024-09-23
2024-07-31
2024-05-28
2024-08-04
2024-04-26
2024-07-09
2024-09-17
2025-04-29
2025-04-29
2025-04-29
2025-04-28
2025-04-28
2025-04-28
2025-04-28
2025-04-28