Programming & Data Formats

How to Fix Common JSON Syntax Errors (And Catch the Bugs That Fail Silently)

A single misplaced comma or unescaped newline will crash a strict JSON parser, while duplicate keys and 64-bit integers can corrupt your data without throwing an error at all. Use this practical guide to decode JSON.parse() exceptions, fix RFC 8259 violations, and format payloads safely in your browser.

How to Fix Common JSON Syntax Errors (And Catch the Bugs That Fail Silently)
Contents
  1. What Your Browser's JSON.parse() Error Actually Means
  2. 6 Everyday Mistakes That Break JSON Files
  3. 1. Leaving a Trailing Comma After the Last Item
  4. 2. Using Single Quotes or Unquoted Keys
  5. 3. Pasting Multi-Line Text or Windows File Paths
  6. 4. Passing NaN, Infinity, or Leading Zeros
  7. 5. Adding // or /* */ Comments
  8. 6. Calling response.json() on an HTML Error Page or Empty Body
  9. 3 Silent JSON Bugs That Pass Validation (And Corrupt Your Data)
  10. 1. Duplicate Keys Overwriting Each Other
  11. 2. Large IDs Losing Their Last Digits (Number.MAX_SAFE_INTEGER)
  12. 3. Double-Stringified Payloads
  13. A Safer Way to Format and Debug Minified JSON in Your Browser
  14. Frequently Asked Questions (FAQ)
  15. Why does my file throw a syntax error at position 0 when the very first character is {?
  16. Is a standalone string or number valid JSON, or does it have to start with {} or []?
  17. Why did JSON.stringify() delete some of the keys from my JavaScript object?

Nothing derails a quick debugging session faster than a JSON parse error. You tweak a configuration file or wire up a fetch() request, and your console immediately throws SyntaxError: Unexpected token } in JSON or Unexpected end of JSON input.

Because JSON has much stricter rules than regular JavaScript objects, a single leftover comma or unescaped line break will stop the parser cold. Even trickier are the bugs that do not throw an error at all—cases where JSON.parse() succeeds quietly, but alters your numbers or overwrites your fields behind the scenes.

Let's walk through what those cryptic parser error messages actually mean in plain English, how to fix the mistakes that trigger them, and how to spot the silent bugs before they hit production.

What Your Browser's JSON.parse() Error Actually Means

JavaScript engines like V8 (Chrome and Node.js), Firefox, and Safari word their exceptions slightly differently—you can see the full browser-by-browser breakdown in MDN's JSON parse error reference. Here is how to translate the most common messages into an immediate fix:

Error Message in Console What Is Really Happening How to Fix It
Unexpected token < in JSON at position 0 Your app expected JSON, but the server sent back an HTML page starting with <!DOCTYPE html> or <html> (usually a 404, 500, or login redirect). Check the Network tab in DevTools. Verify the HTTP status code and URL before calling .json().
Unexpected end of JSON input The string is completely empty (""), got cut off mid-download, or is missing a closing } or ] at the very end. Check for 204 No Content responses, and format the payload to make sure every opening bracket has a matching closing bracket.
Unexpected token ] or Unexpected token } You have a trailing comma right before the closing bracket of an array or object. Delete the comma after the last item in the list.
Expected property name or '}' in JSON A key name is missing double quotes ({id: 1}) or uses single quotes ({'id': 1}). Wrap every key name in standard double quotes ({"id": 1}).
Expected ',' or '}' after property value You forgot a comma between two properties, or you have an unescaped quote (") sitting inside a string. Add the missing comma between lines, or escape inner quotes with \".
Bad control character in string literal A string contains a raw line break (pressing Enter) or a literal tab character. Replace raw line breaks inside strings with \n and tabs with \t.

6 Everyday Mistakes That Break JSON Files

If you spend all day writing JavaScript, TypeScript, or Python, your muscle memory will eventually trick you into writing syntax that works fine in code but fails in a .json file.

1. Leaving a Trailing Comma After the Last Item

Modern code formatters often add a comma after the last item in a JavaScript array or object so future Git diffs stay clean. JSON does not allow that. Every comma must be followed by another item.

// Breaks: commas after "pro" and true
{
  "plans": ["free", "pro",],
  "autoRenew": true,
}

// Works
{
  "plans": ["free", "pro"],
  "autoRenew": true
}

2. Using Single Quotes or Unquoted Keys

In JavaScript, { status: 'ok' } is completely fine. In JSON, both the key name and the string value have to be wrapped in double quotes—no exceptions.

// Breaks: unquoted key and single quotes
{
  status: 'ok',
  'environment': 'production'
}

// Works
{
  "status": "ok",
  "environment": "production"
}

3. Pasting Multi-Line Text or Windows File Paths

Two things frequently break string values: pressing Enter inside a string, and pasting Windows file paths with single backslashes.

Because JSON uses the backslash (\) as an escape character, a path like "C:\temp\notes.txt" gets misread—the parser sees \t as a tab and \n as a newline. Raw line breaks and unescaped control characters (U+0000 through U+001F) are also banned by the official JSON specification (RFC 8259).

// Breaks: raw line break and unescaped backslashes
{
  "message": "Hello
World",
  "exportDir": "C:\temp\new_reports"
}

// Works: use \n for line breaks and \\ for literal backslashes
{
  "message": "Hello\nWorld",
  "exportDir": "C:\\temp\\new_reports"
}

4. Passing NaN, Infinity, or Leading Zeros

Numbers in JSON have to be plain decimal digits:

  • Watch out for Python's NaN and Infinity: By default, Python's json.dumps() will happily output NaN or Infinity when serializing float data. Browser JSON.parse() calls will immediately crash on those values. Pass allow_nan=False in Python or convert missing numbers to null.
  • Drop leading zeros: Write 42, never 042. And if a decimal is less than one, include the leading zero (0.25, not .25).

5. Adding // or /* */ Comments

It is tempting to drop a quick // TODO comment inside a JSON config file, especially since editors like VS Code allow comments in their own settings files (JSONC). Standard JSON parsers, however, treat / as an illegal character outside of a string. If you need to leave a note for your team inside a strict JSON file, add a regular property like "_note": "Keep timeout under 30 seconds".

6. Calling response.json() on an HTML Error Page or Empty Body

Look closely at the error Unexpected token < in JSON at position 0. That < character is almost always the opening bracket of <!DOCTYPE html>.

When an API route crashes with a 500 Internal Server Error, hits a CDN firewall page, or returns a 404, the server usually sends back HTML instead of JSON. You will also get an Unexpected end of JSON input error if your API returns a 204 No Content status (like after a DELETE request) and your front-end code blindly calls response.json() on the empty body.

A small helper function prevents both crashes:

async function fetchJsonSafely(url) {
  const response = await fetch(url);

  // 204 No Content has an empty body
  if (response.status === 204) {
    return null;
  }

  const contentType = response.headers.get("content-type") || "";
  if (!response.ok || !contentType.includes("application/json")) {
    const textPreview = (await response.text()).slice(0, 100);
    throw new Error(`HTTP ${response.status} — expected JSON, got: ${textPreview}`);
  }

  return response.json();
}

3 Silent JSON Bugs That Pass Validation (And Corrupt Your Data)

Syntax errors are noisy, which makes them easy to catch. The bugs that cause real headaches are the ones that are 100% valid JSON syntax, so they sail right past validators and corrupt data quietly.

1. Duplicate Keys Overwriting Each Other

What happens if a JSON object accidentally defines the same key twice? Most developers assume JSON.parse() will throw a duplicate-key error. It does not.

As noted in MDN's JSON.parse() documentation, JavaScript simply keeps the last value and throws the earlier one away without a warning:

const raw = '{"username": "sam", "role": "guest", "role": "admin"}';
console.log(JSON.parse(raw));
// Output: { username: 'sam', role: 'admin' }

This commonly happens when merging configuration blocks by hand or generating JSON strings via string concatenation instead of a real serializer.

2. Large IDs Losing Their Last Digits (Number.MAX_SAFE_INTEGER)

JavaScript reads all JSON numbers as 64-bit floating-point values. That means any integer larger than 9007199254740991 (Number.MAX_SAFE_INTEGER) cannot be represented accurately. Instead of throwing an overflow error, JSON.parse() rounds the last digits silently:

const webhookPayload = '{"orderId": 9007199254740993}';
console.log(JSON.parse(webhookPayload));
// Output: { orderId: 9007199254740992 } — the ID just changed!

If your database or third-party API uses 64-bit integers (such as Snowflake IDs, Stripe/Twitter IDs, or bigints), always send them inside quotes as strings ("orderId": "9007199254740993").

3. Double-Stringified Payloads

If a backend endpoint calls JSON.stringify() on data that was already a JSON string, you end up with a string literal wrapped in extra quotes and backslashes:

"{\"userId\": 18, \"verified\": true}"

When your front end runs const data = JSON.parse(responseBody), it succeeds without error—but typeof data is "string", not "object". When your code checks data.userId, it gets undefined. Whenever properties come back undefined on a response that looks valid in the console, check typeof data first.

A Safer Way to Format and Debug Minified JSON in Your Browser

Trying to spot a missing comma on character 18,402 of a minified, single-line API response is a waste of time. You need a formatter to expand the tree—but you also need to be careful where you paste that data. Many online formatters send your text to a backend server for processing, which is a serious privacy risk if your payload contains live JWT tokens, API keys, or customer emails.

You can format and inspect payloads locally using the Varkido JSON Formatter. Because it runs entirely inside your browser, your data never leaves your device:

  1. Paste your minified or raw JSON into the input box.
  2. Pick your indentation level (such as 2 spaces) to turn a wall of text into a clean, readable hierarchy.
  3. Choose how to handle object keys: Keep Keep original order when you want to see the exact structure returned by your API, or switch to Sort alphabetically when you are trying to compare two objects whose keys were serialized in a different order.
  4. Copy or download: Grab the formatted output with one click, or download it directly as a .json file.

If you are working through a larger debugging workflow, a few companion tools on Varkido can save you extra steps:

  • Check broken syntax: Run suspicious config files through the Varkido JSON Validator to confirm they are valid before deploying.
  • Compare two API responses: After sorting keys alphabetically in the formatter, drop your staging and production payloads into the Varkido JSON Diff Checker to highlight exactly which fields changed.
  • Shrink files for production: Strip whitespace back out with the Varkido JSON Minifier, or build valid application/ld+json SEO scripts from scratch using the Varkido Schema Markup Generator.

Frequently Asked Questions (FAQ)

Why does my file throw a syntax error at position 0 when the very first character is {?

Your text editor likely saved the file with an invisible UTF-8 Byte Order Mark (BOM) at the start of the file. Standard JSON parsers reject files that begin with a BOM. In your code editor (like VS Code or Notepad++), change the file encoding from UTF-8 with BOM to plain UTF-8 and save it again.

Is a standalone string or number valid JSON, or does it have to start with {} or []?

A single string ("hello"), number (42), boolean (true), or null is valid JSON on its own. That said, almost every REST API wraps responses in a top-level object ({"data": ...}) so new fields can be added later without breaking existing clients.

Why did JSON.stringify() delete some of the keys from my JavaScript object?

JSON has no concept of undefined, functions, or Symbol values. If an object property is set to undefined (for example, { name: "Ali", phone: undefined }), JSON.stringify() strips the phone key out completely. If you want the key to stay in the JSON output with an empty value, set it to null instead of undefined.

Contact Varkido: Contactvarkido@gmail.com | +212 681 141 692