Python调用OpenAI接口返回含json前缀内容的处理及写入txt方案
解决GPT-4-Vision返回带前缀的JSON解析错误问题
问题描述
调用OpenAI的gpt-4-vision-preview接口分析图片,要求返回JSON格式结果,但实际返回内容带有json前缀(通常是代码块标记```json),使用json.loads()解析时触发JSONDecodeError,错误信息如下:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案
先清理返回内容中的多余前缀(及可能存在的代码块后缀),再进行JSON解析和文件写入:
- 新增清理函数,去除返回内容中的
```json开头标记和```结尾标记,同时兼容单纯的json前缀情况; - 获取接口返回结果后,先执行清理操作,再写入文件和解析JSON。
修改后的完整代码
import json import os import base64 import openai def clean_json_response(raw_content): # 处理GPT返回的代码块格式JSON if raw_content.startswith("```json"): raw_content = raw_content[7:] # 移除开头的```json # 移除结尾的```标记 if raw_content.endswith("```"): raw_content = raw_content.rstrip("```").strip() # 处理单纯的"json"前缀情况 elif raw_content.strip().startswith("json"): raw_content = raw_content.strip()[4:].strip() return raw_content def get_json(image_file, category): with open(image_file, "rb") as image: response = openai.chat.completions.create( model="gpt-4-vision-preview", messages=[ { "role": "user", "content": [ {"type": "text", "text": f"Analyze this image and provide the following attributes: color theme, font style, and a short description of about 4-7 words. Categorize it as {category}. Return the result as a JSON object."}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64.b64encode(image.read()).decode()}"}}, ], } ], temperature=1, max_tokens=4095, top_p=1, frequency_penalty=0, presence_penalty=0, ) return response.choices[0].message.content # 替换为你的实际文件路径 file_path = "output.txt" images_folder = "path/to/your/images" with open(file_path, 'a') as file: for filename in os.listdir(images_folder): filepath = os.path.join(images_folder, filename) raw_result = get_json(filepath, 'hero') cleaned_result = clean_json_response(raw_result) # 写入合法JSON内容 file.write(cleaned_result + '\n') # 解析并打印结果 json_result = json.loads(cleaned_result) print(json_result)
说明
- 清理函数
clean_json_response覆盖了两种常见异常格式:带代码块标记的```json ... ```和单纯前缀json ...; - 修改后写入文件的内容是合法JSON字符串,后续可直接读取解析;
- 需替换代码中
file_path和images_folder为你的实际路径。
内容的提问来源于stack exchange,提问作者Lovish Bansal
相关产品推荐
相关产品推荐

