Mastering the Resolution of "NodeJS SyntaxError: Unexpected Token X in JSON at Position Y"
Introduction
In the vast landscape of Node.js development, parsing JSON is a common operation. However, developers often face the daunting "SyntaxError: Unexpected token X in JSON at position Y." This error typically arises when JSON parsing fails due to invalid format, unexpected characters, or data corruption. In this comprehensive blog, we'll demystify this error, providing practical scenarios and solutions, alongside strategies and best practices to help you navigate and resolve it efficiently.
// ✅ Use double quotes in JSON
const data = JSON.parse('{ "name": "John" }');
// ✅ Remove trailing commas
const config = JSON.parse('{ "port": 3000 }');
// ✅ Remove comments from JSON
const jsonStr = '{ "debug": true /* comment */ }'.replace(/\/\*[\s\S]*?\*\//g, '');
const settings = JSON.parse(jsonStr);
// ✅ Safe JSON parsing with error handling
function safeParse(str) {
try {
return { data: JSON.parse(str), error: null };
} catch (err) {
return { data: null, error: err.message };
}
}
const result = safeParse('invalid json');
if (result.error) {
console.error('Parse error:', result.error);
}
// ✅ Read and parse JSON files safely
const fs = require('fs');
try {
const raw = fs.readFileSync('config.json', 'utf-8');
const config = JSON.parse(raw);
} catch (err) {
console.error('Config error:', err.message);
}
Understanding the Error
The "SyntaxError: Unexpected token X in JSON at position Y" in Node.js occurs while parsing JSON strings with JSON.parse(). The 'X' represents the unexpected character, while 'Y' indicates its position in the string. This error points to a deviation from the standard JSON format, making it vital to scrutinize the JSON structure closely.
// Invalid JSON: single quotes instead of double quotes
const data = JSON.parse("{ 'name': 'John' }");
// SyntaxError: Unexpected token ' in JSON at position 2
// Trailing comma in JSON
const config = JSON.parse('{ "port": 3000, }');
// SyntaxError: Unexpected token } in JSON at position 17
// Comments in JSON
const settings = JSON.parse('{ "debug": true /* comment */ }');
// SyntaxError: Unexpected token / in JSON
Diving Deeper
JSON parsing errors can stem from various sources, including incorrect data types, extra commas, unescaped characters, or even an improper string format. Let's dive deeper into the common scenarios where this error occurs and explore how to fix them.
Common Scenarios and Fixes with Example Code Snippets
Scenario 1: Extra or Missing Comma
Problem: An extra or missing comma in a JSON string.
const json = '{"name": "Alice", "age": 30,}'; // Trailing comma
const data = JSON.parse(json); // SyntaxError: Unexpected token }
Solution: Remove extra commas and ensure proper JSON formatting.
const json = '{"name": "Alice", "age": 30}'; // No trailing comma
const data = JSON.parse(json);
console.log(data); // { name: 'Alice', age: 30 }
// Always validate JSON before parsing
function safeJsonParse(str) {
try {
return { data: JSON.parse(str), error: null };
} catch (err) {
return { data: null, error: err.message };
}
}
Scenario 2: Unquoted Keys
Problem: Keys in a JSON object must be in double quotes.
const json = '{name: "Alice"}'; // Keys must be quoted in JSON
const data = JSON.parse(json); // SyntaxError
Solution: Ensure all keys are appropriately quoted.
const json = '{"name": "Alice"}'; // Keys must be double-quoted
const data = JSON.parse(json);
console.log(data.name); // 'Alice'
Scenario 3: Single Quoted Strings
Problem: JSON strings must use double quotes.
const json = "{'name': 'Alice'}"; // JSON requires double quotes
const data = JSON.parse(json); // SyntaxError
Solution: Replace single quotes with double quotes.
const json = '{"name": "Alice"}'; // Use double quotes for JSON strings
const data = JSON.parse(json);
console.log(data.name); // 'Alice'
Scenario 4: Invalid Data Types
Problem: JSON does not support certain data types like functions or undefined.
const json = '{"value": undefined}'; // undefined is not valid JSON
const data = JSON.parse(json); // SyntaxError
Solution: Remove or replace unsupported data types.
const json = '{"value": null}'; // Use null instead of undefined
const data = JSON.parse(json);
console.log(data.value); // null
Scenario 5: Improperly Escaped Characters
Problem: Special characters in JSON strings must be escaped.
const json = '{"path": "C:\users\docs"}'; // Backslashes not escaped
const data = JSON.parse(json); // SyntaxError
Solution: Escape special characters correctly.
const json = '{"path": "C:\\users\\docs"}'; // Double-escape backslashes
const data = JSON.parse(json);
console.log(data.path); // 'C:\users\docs'
// Or build JSON safely with JSON.stringify
const obj = { path: 'C:\\users\\docs' };
const safeJson = JSON.stringify(obj);
Scenario 6: Trailing Non-JSON Content
Problem: Additional non-JSON content following valid JSON.
// HTML returned instead of JSON (e.g., error page)
const response = '<html><body>Not Found</body></html>';
const data = JSON.parse(response); // SyntaxError: Unexpected token <
Solution: Remove any non-JSON content.
const response = '<html><body>Not Found</body></html>';
// Check content before parsing
function parseResponse(text) {
const trimmed = text.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
try {
return JSON.parse(trimmed);
} catch (err) {
console.error('Invalid JSON:', err.message);
return null;
}
}
console.error('Response is not JSON:', trimmed.substring(0, 100));
return null;
}
Scenario 7: Corrupted JSON Data
Problem: The JSON string is corrupted or partially missing.
const fs = require('fs');
// File partially written or corrupted
const raw = fs.readFileSync('data.json', 'utf8');
// raw = '{"users": [{"name": "Alice"}, {"name": "Bob' (truncated)
const data = JSON.parse(raw); // SyntaxError
Solution: Ensure the integrity of the JSON data.
const fs = require('fs');
function readJsonFile(filePath) {
try {
const raw = fs.readFileSync(filePath, 'utf8');
return JSON.parse(raw);
} catch (err) {
if (err.code === 'ENOENT') {
console.error('File not found:', filePath);
} else if (err instanceof SyntaxError) {
console.error('Corrupted JSON in', filePath);
console.error('Error:', err.message);
// Try to recover from backup
try {
return JSON.parse(fs.readFileSync(filePath + '.bak', 'utf8'));
} catch { return null; }
}
return null;
}
}
Scenario 8: Inappropriate Data Encoding
Problem: Incorrect encoding of the JSON string data.
const fs = require('fs');
// Reading a UTF-16 file as UTF-8
const raw = fs.readFileSync('data-utf16.json'); // Buffer with BOM
const data = JSON.parse(raw.toString()); // SyntaxError due to BOM
Solution: Decode or format the data correctly.
const fs = require('fs');
// Handle different encodings
let raw = fs.readFileSync('data.json', 'utf8');
// Remove BOM (Byte Order Mark) if present
if (raw.charCodeAt(0) === 0xFEFF) {
raw = raw.substring(1);
}
const data = JSON.parse(raw);
console.log(data);
Strategies to Prevent Errors
Data Validation: Before parsing, validate the JSON string using regular expressions or schema validators.
Safe Parsing: Use try-catch blocks to handle parsing errors gracefully.
Stringification Practices: When creating JSON strings, use JSON.stringify() to avoid manual errors.
Best Practices
Consistent Formatting: Adhere to standard JSON formatting rules.
Logging and Monitoring: Implement logging to trace the origin of malformed JSON.
Use of Libraries: Utilize robust JSON parsing libraries that offer additional error information.
Conclusion
Understanding and resolving "SyntaxError: Unexpected token X in JSON at position Y" requires attention to JSON standards and careful data handling. By applying the strategies and best practices outlined here, developers can effectively manage JSON data in Node.js, ensuring efficient and error-free applications. Remember, meticulous JSON handling is a hallmark of proficient Node.js development.
Written by
Divya Mahi
Building innovative digital solutions at Poulima InfoTech. We specialize in web & mobile app development using React, Next.js, Flutter, and AI technologies.
Ready to Build Your Next Project?
Transform your ideas into reality with our expert development team. Let's discuss your vision.
