使gpt输出的数据严格符合json格式,不要出现【转义/换行符/其余文字/解释】
解决方法一:把prompt写的更严格
加入这么一句:
Ensure the output is a valid JSON object in a compact format without any additional explanations, escape characters, newline characters, or backslashes.
确保输出是紧凑格式的有效 JSON 对象,不包含任何其他解释、转义符、换行符或反斜杠。
解决方法二 从代码方面进行json订正(json格式订正+while循环):
每次生成一条新的数据后:
- 对数据进行json格式订正。
- 若对数据进行json格式订正后,仍然不符合我们规定的输出的格式(生成质量差)
- while循环让其重新根据这个数据进行生成。
伪代码思想:
在处理每个图像时,使用while True循环,直到生成正确的JSON格式为止。
- 每次gpt输出后,输入订正JSON格式函数中
- 如果生成的JSON格式(订正后)正确,跳出循环继续处理下一个图像。
- 如果生成的JSON格式不正确,打印错误信息并重新处理当前图像。
代码实现细节:
1. 先while循环和(try-catch):
现在输入一张要处理的图像:
- 调用GPT
- GPT输出内容输入【订正json格式的函数】
- 如果订正后JSON格式正确,把其保存(以json对象进行保存(更稳定)),break跳出循环
- 如果订正JSON格式后仍然不正确,重新while循环处理当前图像
# 现在输入一张要处理的图像
while True:
try:
# 调用GPT
response = chat_completions(image_file)
# GPT结果输入订正json格式函数
# 记得输入:response.choices[0].message.content
cleaned_json = clean_and_validate_json(response.choices[0].message.content)
# 如果订正后json格式正确,把其保存
if cleaned_json:
result = {image_name: cleaned_json}
# 每次处理一个图像后就打开输出文件并更新结果(以json对象进行保存)
with open(output_file_path, "a") as output_file:
output_file.write(json.dumps(result) + "\n")
break # 如果JSON格式正确,跳出循环
else:
continue # 如果JSON格式不正确,重新处理当前图像
except Exception as e:
continue
2. 订正json格式函数
- 希望gpt生成的json格式案例:
{
"image_id": "image123",
"translations": [
{
"text": "Hello, World!",
"language": "en"
},
{
"text": "Bonjour le monde!",
"language": "fr"
}
]
}
- 订正流程(用正则表达式(不会破坏json结构)):
- 去除不可见字符
- 去除多余的空格/换行符/转义字符
- 将单引号全部替换为双引号
- 尝试修复常见的JSON格式问题(确保 key 和 value 是用双引号括起来的)
- 尝试加载json对象,并确保其包含所需的键
# output是gpt生成的response.choices[0].message.content
def clean_and_validate_json(output):
# 去除不可见字符
output = re.sub(r'[\x00-\x1F\x7F]', '', output)
# 使用正则表达式去除多余的空格和换行符
output = re.sub(r'\s+', ' ', output).strip()
# 将单引号替换为双引号
output = output.replace("'", '"')
# 尝试修复常见的 JSON 格式问题
# 确保 key 和 value 是用双引号括起来的
output = re.sub(r'(\w+)\s*:\s*([^",{}\[\]]+)', r'"\1": "\2"', output)
try:
json_obj = json.loads(output)
if 'image_id' in json_obj and 'translations' in json_obj:
for translation in json_obj['translations']:
if 'text' not in translation or 'language' not in translation:
return None
return json_obj
else:
return None
except json.JSONDecodeError:
return None