LiveCode应用对接ChatGPT接口报错:JSON请求解析失败求修复
解决LiveCode调用ChatGPT API的JSON格式错误问题
你的问题核心是手动拼接的JSON格式不符合规范,导致OpenAI API无法解析。LiveCode提供了专门的JSON处理函数,用它生成请求体可以彻底避免这类问题。以下是修复后的完整代码:
on mouseUp put "<my personal API key>" into api_key put "2 + x = 10, what is x?" into tQuestion put "https://api.openai.com/v1/chat/completions" into tURL -- 构建请求头 put "Bearer" && api_key into tAuthorization set the httpHeaders to "Authorization:" && tAuthorization & cr & "Content-Type: application/json" -- 构建请求体的数组结构 put "gpt-3.5-turbo" into tRequestA["model"] put "user" into tRequestA["messages"][1]["role"] put tQuestion into tRequestA["messages"][1]["content"] -- 将数组编码为标准JSON字符串 jsonEncode tRequestA into tBody -- 发送POST请求并处理响应 post tBody to url tURL if the result is empty then put it into field "Response" else put "请求错误: " & the result into field "Response" end if end mouseUp
关键修复点说明:
- 用数组+
jsonEncode生成JSON:手动拼接字符串极易出现引号、逗号、换行符等格式错误,通过数组定义结构再编码,能确保生成的JSON完全符合规范。 - 修正HTTP请求写法:将
post tBody to tURL改为LiveCode标准写法post tBody to url tURL,避免潜在的解析问题。 - 增加错误处理:添加请求结果判断,网络或API调用出错时能显示具体错误信息,方便排查问题。
额外注意事项:
- 替换代码中的
<my personal API key>为你实际的OpenAI API密钥。 - 确保你的LiveCode版本支持
jsonEncode函数(LiveCode 7及以上版本均支持)。 - 若需发送多轮对话消息,只需在
tRequestA["messages"]数组中添加更多元素即可,示例:put "assistant" into tRequestA["messages"][2]["role"] put "x is 8" into tRequestA["messages"][2]["content"] put "user" into tRequestA["messages"][3]["role"] put "What is 3 * x?" into tRequestA["messages"][3]["content"]
内容的提问来源于stack exchange,提问作者John P. Arrow
相关产品推荐
相关产品推荐

