invalid extra content: unexpected end of JSON input

2025年11月25日 10:49 状态: processing

🚨 错误信息

invalid extra content: unexpected end of JSON input

🤖 AI解决方案

错误翻译

原文:unexpected end of JSON input
译文:JSON输入意外结束

原因分析

这是一个典型的JSON解析错误,发生在尝试解析不完整的JSON数据时。根本原因是JSON字符串在解析过程中提前结束,缺少必要的闭合符号(如缺少闭合的花括号}或方括号])。

解决方案

方案1:添加JSON数据完整性检查

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数据

// 如果JSON缺少闭合花括号
const incompleteJson = '{"name": "John", "age": 30'; // 缺少 }
const fixedJson = incompleteJson + '}';

// 如果JSON缺少闭合方括号
const incompleteArray = '["apple", "banana"'; // 缺少 ]
const fixedArray = incompleteArray + ']';

️ 预防措施

  • 数据验证:在解析JSON前,先验证数据来源的完整性,确保网络请求或文件读取完全完成
  • 使用JSON验证工具:在开发过程中使用ESLint插件或在线JSON验证器检查JSON格式的正确性