Unexpected token 'A', "Alright, l"... is not valid JSON at JSON.parse (<anonymou...
🚨 错误信息
文本请求成功完成
geminiService.ts:213
原始AI响应:
Alright, let's get down to brass tacks. I've got a movie script on my hands, and I need a structured analysis. I'm thinking a clean, JSON output is the way to go. Here's what I want to pull out of this thing, and how I'm going to organize it:
First, a high-level `summary` – a concise encapsulation of the narrative itself. Think a distilled essence of the story, easily grasped.
Then, I'll need a section for `characters`. This is crucial. Each entry in the array will represent a main character.
错误
geminiService.ts:218
JSON解析失败:
JSON解析失败: SyntaxError: Unexpected token 'A', "Alright, l"... is not valid JSON
at JSON.parse (<anonymous>)
at analyzeScript (geminiService.ts:215:36
)
at async handleAnalyze (App.tsx:214:22)
错误
App.tsx:241
Error: Failed to parse AI response as JSON at analyzeScript (http://localhost:3001/services/geminiService.ts?t=1765817669356:167:11) at async handleAnalyze (http://localhost:3001/App.tsx?t=1765817669356:190:22)
Error: Failed to parse AI response as JSON
at analyzeScript (geminiService.ts:219:15
)
at async handleAnalyze (App.tsx:214:22)
🤖 AI解决方案
代码报错分析
1. 错误翻译
原文:JSON解析失败: SyntaxError: Unexpected token 'A', "Alright, l"... is not valid JSON
译文:JSON解析失败:语法错误:意外的标记 'A',"Alright, l"... 不是有效的JSON格式
2. 原因分析
根本原因:AI模型返回的响应是纯文本(自然语言),而不是预期的JSON格式。错误位置:
geminiService.ts:213- AI模型的原始响应是自然语言文本geminiService.ts:218- 尝试解析非JSON文本时发生错误analyzeScript函数在行215-219处尝试使用JSON.parse()解析响应- 请求发送给AI服务(可能是Gemini模型)
- AI返回了自然语言响应(以"Alright, let's get down to brass tacks..."开头)
- 代码期望JSON格式,直接调用
JSON.parse()解析自然语言文本 - 由于文本不是有效的JSON格式,解析失败
上下文分析:
3. 解决方案
方案一:修改AI请求提示词(推荐)
// geminiService.ts
async function analyzeScript(content: string) {
try {
// 在发送给AI的提示词中明确要求JSON格式
const prompt = `请分析以下电影剧本,并返回严格的JSON格式数据,包含以下字段:
{
"summary": "剧本概要",
"characters": [
{
"name": "角色名",
"description": "角色描述"
}
]
}
剧本内容:${content}
请只返回JSON,不要有任何其他文本。`;
const aiResponse = await geminiAPI.sendPrompt(prompt);
const parsedData = JSON.parse(aiResponse);
return parsedData;
} catch (error) {
// 错误处理逻辑
}
}
方案二:添加响应验证和清理
// geminiService.ts
async function analyzeScript(content: string) {
try {
const aiResponse = await geminiAPI.sendPrompt(`分析剧本:${content}`);
// 提取JSON部分(如果AI在文本中嵌入了JSON)
const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsedData = JSON.parse(jsonMatch[0]);
return parsedData;
} else {
// 如果找不到JSON,尝试清理后解析
const cleanedResponse = aiResponse
.replace(/^[^{]*/, '') // 移除JSON前的文本
.replace(/[^}]*$/, ''); // 移除JSON后的文本
if (cleanedResponse.trim().startsWith('{')) {
const parsedData = JSON.parse(cleanedResponse);
return parsedData;
} else {
throw new Error('AI响应不包含有效的JSON格式');
}
}
} catch (error) {
// 错误处理逻辑
}
}
4. ️ 预防措施
️ 最佳实践:
推荐工具:
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}