โ† Back to Blog

How to Debug JSON Errors

2026-04-10 ยท 5 min read

Common Sources of JSON Errors

JSON errors typically come from: syntax errors introduced during manual JSON editing; improper handling when concatenating JSON strings in code; conversion from other formats (like JavaScript object literals) carrying syntax JSON doesn't support; invalid characters from encoding issues; malformed responses from third-party APIs; configuration files that had errors introduced during manual editing.

Understanding error sources helps you target your debugging rather than blindly searching the entire JSON.

Reading Error Messages: JSON Errors in Each Language

JavaScript: JSON.parse() throws SyntaxError: Unexpected token X in JSON at position N, where N is the character offset (0-indexed) and X is the unexpected character.

Python: json.loads() throws json.decoder.JSONDecodeError: Expecting X: line Y column Z (char N) โ€” directly gives line and column numbers, making it easier to locate.

Go: json.Unmarshal() returns &json.SyntaxError{Offset: N} containing the byte offset.

Python gives the friendliest error messages (line and column directly); JavaScript gives a character offset (need to count characters or use a text editor to locate); Go gives the least detail.

Debugging Steps: A Systematic Approach

  1. Get the complete error message: Make sure you're seeing the full error message including line/position information. Don't stop at just "JSON parse error."
  2. Isolate the problematic JSON: Log the failing JSON string so you're debugging the actual failing data โ€” not what you think it should look like.
  3. Use an online validation tool: Paste the JSON into an online formatter/validator โ€” it will precisely indicate the error location and type.
  4. Check common error spots: Focus on the commas, quotes, and brackets immediately around the error position.
  5. Test incrementally: For large JSON, start from a known-correct section and gradually add content, finding the exact point where the error was introduced.

Invisible Characters: The Hardest-to-Diagnose Problem

Sometimes JSON looks completely correct but still fails to parse, possibly due to invisible characters: BOM (Byte Order Mark) is sometimes appended to the beginning of UTF-8 files (especially those created on Windows) โ€” JSON parsers can't handle it; Zero-Width Space (U+200B) occasionally appears in text copied from web pages; HTML entities (like &, ") appearing where plain JSON should be โ€” usually because JSON was incorrectly HTML-escaped.

Solutions: use a hex editor to view the actual byte content; display invisible characters in a formatting tool; strip BOM in code: text.replace(/^\uFEFF/, '') (JavaScript).

Debugging JSON Errors in API Responses

When an API response's JSON fails to parse, check these prerequisites first: Is the HTTP response status code 200? Non-200 responses (404, 500) may return HTML error pages instead of JSON. Is the Content-Type response header application/json? If the server returned an error, it may be text/html. Is the response body empty? An empty response body is not valid JSON.

In Chrome Developer Tools' Network panel, you can directly view the raw response text and the parsed JSON (Preview tab). If the Preview tab shows an error, switch to the Raw tab to see the raw response content โ€” this usually quickly reveals the problem.

Common Errors When Generating JSON in Code

Manually concatenating JSON strings in code is the most error-prone approach. The correct approach is to always use the language's built-in JSON serialization methods (JSON.stringify(), json.dumps(), json.Marshal()) rather than string concatenation:

// ้”™่ฏฏๅšๆณ• / Wrong:
const json = '{"name": "' + name + '", "age": ' + age + '}';
// ๅฆ‚ๆžœ name ๅŒ…ๅซๅŒๅผ•ๅทๆˆ–ๆข่กŒ๏ผŒไผšไบง็”Ÿๆ— ๆ•ˆ JSON

// ๆญฃ็กฎๅšๆณ• / Correct:
const json = JSON.stringify({name, age});
// JSON.stringify ไผš่‡ชๅŠจๅค„็†ๆ‰€ๆœ‰็‰นๆฎŠๅญ—็ฌฆ็š„่ฝฌไน‰

Defensive Programming: Handling JSON Errors Gracefully

In production code, JSON parsing should be wrapped in try-catch with meaningful error information:

function safeParseJSON(str, context = '') {
  try {
    return { data: JSON.parse(str), error: null };
  } catch (e) {
    console.error(`JSON parse failed [${context}]:`, e.message);
    console.error('Raw input (first 200 chars):', str?.slice(0, 200));
    return { data: null, error: e.message };
  }
}

Logging the first 200 characters of the raw input (not all of it, to avoid bloated logs) is an effective technique for investigating JSON problems โ€” it helps quickly identify root causes in production environments.

Try the free tool now

Use Free Tool โ†’