invalid extra content: unexpected end of JSON input
🚨 错误信息
invalid extra content: unexpected end of JSON input
🤖 AI解决方案
错误翻译
原文:unexpected end of JSON input
译文:JSON输入意外结束
原因分析
这是一个典型的JSON解析错误,发生在尝试解析不完整的JSON数据时。根本原因是JSON字符串在解析过程中提前结束,缺少必要的闭合符号(如缺少闭合的花括号}或方括号])。
解决方案
方案1:添加JSON数据完整性检查
javascript
function parseJSONSafely(jsonString) {
try {
// 检查JSON字符串是否完整
const trimmed = jsonString.trim();
if (trimmed.length === 0) {
throw new Error('JSON字符串为空');
}
// 检查基本的结构完整性
if ((trimmed.startsWith('{') && !trimmed.endsWith('}')) ||
(trimmed.startsWith('[') && !trimmed.endsWith(']'))) {
throw new Error('JSON结构不完整');
}
return JSON.parse(jsonString);
} catch (error) {
console.error('JSON解析失败:', error.message);
return null;
}
}// 使用示例
const result = parseJSONSafely(yourJsonString);
方案2:修复不完整的JSON数据
javascript
// 如果JSON缺少闭合花括号
const incompleteJson = '{"name": "John", "age": 30'; // 缺少 }
const fixedJson = incompleteJson + '}';// 如果JSON缺少闭合方括号
const incompleteArray = '["apple", "banana"'; // 缺少 ]
const fixedArray = incompleteArray + ']';