如何将openai调用的结果转换为json并写入.txt文件?

问题描述 投票:0回答:1

我对 python 很陌生,只知道基础知识,所以基本上我正在调用 openai 并获得响应作为回报,并希望将该响应写入 .txt 文件中。

我想在写入文件之前将响应转换为 json 格式。我的回复已经是 json 格式,但打印时很奇怪,它显示 json 格式,并带有

json {} 
,这是我的脚本

def get_json(image_file, category):
    with open(image_file, "rb") as image:
        response = openai_client.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
     
with open(file, 'a') as file:
    for filename in os.listdir(images_folder):
        filepath = os.path.join(images_folder, filename)
        result =get_json(filepath, 'hero')
        file.write(result + '\n')
        json_result = json.loads(result)
        print(json_result)

这就是我得到的结果 在此输入图片描述

我想删除文本 '''json'''

尝试通过

json.loads(result)
将其转换为json,但出现以下错误:- 从 None 引发 JSONDecodeError("期望值", s, err.value) json.decoder.JSONDecodeError:期望值:第1行第1列(字符0)

python json openapi
1个回答
0
投票

您要求它在提示中返回一个 JSON 对象,“将结果作为 JSON 对象返回”。这就是为什么!如果您使用网站给出相同的提示,您会注意到响应的格式很好,这是因为那些“````json ...content``”markdown 格式。

可以用两种方法解决:

  1. 将“```json”和“```”显式替换为空字符串:
import json

# For example, this is the content in response:
response = '```json{"color_theme": "Mint Green and Black","font_style": "Sans-serif","short_description": "Web Publishing Platform","category": "hero"}```'

# Replace and assign back to original content
response = response.replace("```json", "")
response = response.replace("```", "")

# Don't forget to convert to JSON as it is a string right now:
json_result = json.loads(response)
  1. 使用切片:
import json

# For example, this is the content in response:
response = '```json{"color_theme": "Mint Green and Black","font_style": "Sans-serif","short_description": "Web Publishing Platform","category": "hero"}```'

# "```json" is 7 character long, but slicing count start from 0. "{" is at 7th character.
# "```" is 3 character long (at the end).
response = response[7:-3]

# Don't forget to convert to JSON as it is a string right now:
json_result = json.loads(response)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.