Web Development

Common JSON Validation Errors and How to Fix Them

Learn about the most frequent JSON syntax errors developers encounter, from trailing commas to mismatched brackets, and discover how to identify and fix them quickly.

By Inventive HQ Team

The most common JSON validation errors are trailing commas, single quotes instead of double quotes, unquoted property names, missing commas, mismatched or missing brackets, unescaped control characters, comments, invalid data types, duplicate keys, and an invisible byte-order mark (BOM) at the start of the file. Almost all of them come from the same root cause: JSON looks like a JavaScript object, but its grammar (defined in RFC 8259) is far stricter — keys and strings must use double quotes, no trailing commas, no comments, and only six data types. The fastest fix for any of them is to pretty-print the JSON, jump to the character position the parser reports, and check the token just before it.

That is the summary an AI overview gives you. What it can't give you is the part that actually saves time in production: exactly which error message maps to which cause (the parser almost never points at the real mistake), how to read a cryptic "Unexpected end of JSON input," and why a file that looks perfect still fails because of a character you can't see. This is a companion to our deeper explainer on what JSON validation is and why it matters — that post covers the two validation layers (syntax vs. JSON Schema); this one is the field guide to the specific errors and their fixes.

Paste your JSON into the validator below to see the exact line, position, and cause — everything runs client-side, nothing is uploaded:

Loading interactive tool...

The fast lookup: symptom → cause → fix

Most JSON errors are one of a small set of mistakes. Find the message you're seeing (exact wording varies by language and engine — V8, Python, Go, and .NET all phrase it differently), then apply the fix. The Points at column is the important one: the parser flags where it gave up, which is usually one token after the real error.

Symptom (typical error message)Root causePoints atFix
Expected double-quoted property name / Unexpected token '}'Trailing comma after the last itemThe closing } or ]Delete the comma after the final element
Unexpected token ' / Expected property nameSingle quotes around a key or stringThe first 'Replace every ' with "
Unexpected token n (or similar letter)Unquoted property name (name: not "name":)First letter of the bare keyWrap every key in double quotes
Unexpected string / Expected ','Missing comma between two elementsThe start of the next elementAdd the comma at the end of the previous line
Unexpected end of JSON inputMissing/mismatched bracket or unterminated stringEnd of filePretty-print, use bracket matching, add the unpaired } ] or "
Bad control character in string literalRaw newline/tab (control char) inside a stringThe literal newline/tabEscape it: \n, \t, \r — or serialize with JSON.stringify
Unexpected token '/'Comment (// or /* */) — not allowed in JSONThe /Remove it; use a _comment field or JSONC/JSON5 if the tool supports it
Unexpected number / Unexpected token 0Invalid number: leading zero (007), hex (0xFF), NaN, InfinityThe bad numberUse plain decimals; null for NaN/Infinity
No error, wrong valueDuplicate keys — last value silently winsNothing (parser accepts it)Make every key in an object unique; validate untrusted input
Unexpected token on a perfect-looking first lineBOM (invisible U+FEFF) at file startColumn 1Save as "UTF-8 without BOM" or strip the leading 
undefined is not valid JSON / Unexpected token uUnsupported type: undefined, function, Date, RegExpThe bad valueConvert to null, a string, or an ISO 8601 date string

The sections below walk through each error with a full before/after example. If you want the underlying rules and the difference between syntax errors and schema errors, read what is JSON validation alongside this.

How to isolate any JSON error in four steps

When a large file fails and the message is cryptic, this loop finds the culprit fast — no guessing.

Four steps to isolate a JSON error A left-to-right flow: Format the JSON, jump to the reported position, check the token just before it, then re-validate — with a marker travelling along the path. Isolate a JSON error in four steps 1 Format Pretty-print it 2 Jump To the position 3 Check before Prev token/line 4 Re-validate Repeat if needed

1. Trailing Commas

The Error

Trailing commas are the most common JSON validation error. While JavaScript allows trailing commas in arrays and objects for developer convenience, the JSON specification explicitly prohibits them. This discrepancy trips up many developers transitioning between JavaScript and JSON.

Invalid:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York",
}

Error message: Unexpected token '}' at position 54

The Fix

Remove any comma after the last item in arrays or objects:

Valid:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}

Prevention Tips

  • Use a JSON validator or linter integrated into your code editor
  • Enable automatic trailing comma removal in your formatter
  • When copying from JavaScript, always validate before using as JSON

2. Single Quotes Instead of Double Quotes

The Error

JSON requires double quotes (") for all strings and property names. Single quotes (') are not valid in JSON, despite being acceptable in JavaScript. This is another frequent source of confusion for JavaScript developers.

Invalid:

{
  'name': 'John Doe',
  'active': true
}

Error message: Unexpected token ' at position 2

The Fix

Replace all single quotes with double quotes:

Valid:

{
  "name": "John Doe",
  "active": true
}

Why This Matters

This strict requirement ensures consistency across all JSON parsers and programming languages. While JavaScript is lenient about quote types, JSON's specification demands uniformity to maintain cross-platform compatibility.

3. Unquoted Property Names

The Error

All object keys (property names) must be enclosed in double quotes. This differs from JavaScript object literals, where quotes around property names are often optional.

Invalid:

{
  name: "John Doe",
  age: 30
}

Error message: Unexpected token 'n' at position 3

The Fix

Wrap all property names in double quotes:

Valid:

{
  "name": "John Doe",
  "age": 30
}

Common Scenario

This error frequently appears when developers copy JavaScript object literals directly into JSON configuration files or API payloads. Modern code editors with JSON mode can highlight unquoted keys as errors.

4. Missing Commas Between Elements

The Error

JSON requires commas to separate array elements and object properties. Forgetting a comma between elements prevents proper parsing.

Invalid:

{
  "firstName": "John"
  "lastName": "Doe"
}

Error message: Unexpected string at position 27

The Fix

Add commas between all elements (except the last one):

Valid:

{
  "firstName": "John",
  "lastName": "Doe"
}
Advertisement

Detection Strategy

When you see "Unexpected string" or "Unexpected token" errors pointing to a valid-looking line, check for a missing comma on the previous line. This pattern reveals most missing comma errors quickly.

5. Mismatched Brackets and Braces

The Error

Every opening bracket [ must have a corresponding closing bracket ], and every opening brace { must have a closing brace }. Mismatched pairs create parsing errors that can be difficult to diagnose in large JSON files.

Invalid:

{
  "users": [
    {"name": "Alice"},
    {"name": "Bob"}
  },
  "total": 2

Error message: Unexpected end of JSON input

The Fix

Ensure every opening bracket/brace has a matching closing bracket/brace:

Valid:

{
  "users": [
    {"name": "Alice"},
    {"name": "Bob"}
  ],
  "total": 2
}

Debugging Technique

Use a JSON validator that shows line numbers and matching pairs. Many code editors provide bracket matching that highlights corresponding opening and closing brackets when you position your cursor on one. For complex nested structures, consider using a JSON formatter that visually indents nested levels.

6. Invalid Number Formats

The Error

JSON supports numbers but has strict formatting rules: no leading zeros (except for 0.x decimals), no hexadecimal notation, and no special values like NaN or Infinity.

Invalid:

{
  "quantity": 007,
  "price": 0xFF,
  "discount": NaN
}

The Fix

Use standard decimal notation and null for invalid numbers:

Valid:

{
  "quantity": 7,
  "price": 255,
  "discount": null
}

Special Cases

  • Leading zeros: 0077
  • Hexadecimal: 0xFF255
  • Not a number: NaNnull
  • Infinity: Infinity → Use a very large number or null
  • Scientific notation: Valid (1.5e10 is allowed)

7. Unsupported Data Types

The Error

JSON only supports six data types: string, number, boolean, null, array, and object. JavaScript features like functions, undefined values, dates, regular expressions, and comments are not valid in JSON.

Invalid:

{
  "name": "John",
  "age": undefined,
  "callback": function() { return true; },
  "created": new Date()
}

The Fix

Convert unsupported types to JSON-compatible equivalents:

Valid:

{
  "name": "John",
  "age": null,
  "callback": null,
  "created": "2025-01-30T10:30:00Z"
}

Conversion Guidelines

  • undefinednull
  • Functions → Remove or convert to string
  • Dates → ISO 8601 string format
  • RegExp → String representation
  • Custom objects → Serialize with toJSON() method

8. Comments in JSON

The Error

Despite JSON's JavaScript heritage, the JSON specification does not support comments. Many developers attempt to add comments for documentation, but parsers reject them.

Invalid:

{
  // User information
  "name": "John Doe",
  /* Age in years */
  "age": 30
}

Error message: Unexpected token '/' at position 3

The Fix

Remove all comments. For documentation, consider:

  1. Using a documentation field:
{
  "_comment": "User information",
  "name": "John Doe",
  "age": 30
}
  1. Maintaining separate documentation files
  2. Using JSONC (JSON with Comments) for configuration files where supported

Alternative Formats

Some modern tools support JSONC (JSON with Comments) for configuration files. Popular examples include VS Code's settings.json and various build tools. However, standard JSON parsers will reject JSONC files, so use this format only where explicitly supported.

9. Invalid Escape Sequences

The Error

String values can contain escape sequences, but only specific sequences are valid: \", \\, \/, \b, \f, \n, \r, \t, and Unicode escapes \uXXXX.

Invalid:

{
  "path": "C:\new\folder",
  "message": "Line 1\xLine 2"
}

The Fix

Use valid escape sequences:

Valid:

{
  "path": "C:\\new\\folder",
  "message": "Line 1\nLine 2"
}

Common Escape Sequences

  • \" - Double quote
  • \\ - Backslash
  • \/ - Forward slash (optional)
  • \n - Newline
  • \t - Tab
  • \r - Carriage return
  • \uXXXX - Unicode character (e.g., \u00A9 for ©)

10. Duplicate Keys

The Error

While not always caught by parsers, duplicate property names within the same object create ambiguity and unpredictable behavior. Different parsers handle duplicates differently—some use the first value, others use the last, and some reject the JSON entirely.

Problematic:

{
  "name": "John Doe",
  "age": 30,
  "name": "Jane Doe"
}

The Fix

Ensure all property names within an object are unique:

Valid:

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 30
}

Why Duplicates Are Dangerous

Even when parsers accept duplicate keys, the resulting behavior is undefined by the JSON specification. In JavaScript, later values typically override earlier ones, but you cannot rely on this across all platforms and languages. Always use unique property names to ensure consistent parsing.

Debugging Strategies for Complex JSON Errors

When facing complex JSON errors in large files, use these systematic approaches:

1. Use a JSON Validator

Online JSON validators provide immediate feedback with line-specific error messages. Our JSON Validator tool highlights errors, shows exact positions, and suggests fixes—all processed securely in your browser.

2. Format First

Before debugging, format your JSON with proper indentation. Properly indented JSON makes structural errors like mismatched brackets immediately visible.

3. Binary Search Technique

For large files with unclear errors:

  1. Comment out (or remove) half the content
  2. Re-validate
  3. If valid, the error is in the removed half; otherwise, it's in the remaining half
  4. Repeat until you isolate the problematic section

4. Check Encoding

Ensure your JSON file uses UTF-8 encoding. Some characters in other encodings cause parsing failures. Hidden characters like byte order marks (BOM) can also trigger cryptic errors.

5. Validate Programmatically

Integrate JSON validation into your development workflow:

try {
  const data = JSON.parse(jsonString);
  console.log('Valid JSON:', data);
} catch (error) {
  console.error('JSON Error:', error.message);
  // Error message includes position information
}

Prevention: Best Practices

Prevent JSON errors before they happen:

  1. Use schema validation: Define JSON schemas and validate against them
  2. Automate formatting: Configure your editor to auto-format JSON on save
  3. Enable linting: Use ESLint with JSON plugins for real-time error detection
  4. Code reviews: Review JSON configuration changes like code
  5. Version control: Track JSON files in git to identify when errors were introduced
  6. Generate programmatically: Use libraries to generate JSON rather than writing it manually
  7. Test thoroughly: Validate JSON in automated tests before deployment

Conclusion

JSON validation errors are common but easily preventable with the right tools and awareness. The most frequent errors—trailing commas, incorrect quotes, and missing commas—can be caught immediately with proper validation tools integrated into your development environment.

By understanding these common pitfalls and implementing systematic debugging strategies, you can quickly identify and fix JSON errors before they impact production systems. Remember: a few seconds spent validating JSON saves hours of production debugging.

Need to validate your JSON right now? Try our free JSON Validator for instant error detection with detailed explanations—no server uploads, completely private and secure.

Frequently Asked Questions

What is the most common JSON error?

The trailing comma is the single most common JSON syntax error. JavaScript allows a comma after the last element of an array or object, but the JSON specification (RFC 8259) explicitly forbids it, so code that copies a JavaScript object literal straight into a JSON file or API body breaks. The error usually reads like "Unexpected token '}'" or "Expected double-quoted property name" and points at the closing bracket rather than the comma itself. The fix is to delete the comma after the final item.

Why does JSON only allow double quotes?

RFC 8259, the JSON standard, defines a string as characters wrapped in double quotes, and property names are strings, so both keys and string values must use double quotes ("). Single quotes (') are a JavaScript convenience that JSON never adopted, which keeps the grammar tiny and unambiguous across every language that parses JSON. Replace every single quote around a key or string value with a double quote. Unquoted keys (name: instead of "name":) are invalid for the same reason.

How do I find where my JSON is invalid?

Most parsers report a character position or line and column with the error, for example "Unexpected token at position 54." Format (pretty-print) the JSON first so each key sits on its own line, then jump to the reported position. A key detail: the parser flags the point where it gave up, which is often one token after the real mistake — a missing comma is reported on the next line, not the line that is actually missing the comma. When the position is unclear, use a validator that highlights the exact spot or bisect the file by removing half and re-validating.

Are comments allowed in JSON?

No. The JSON specification does not support comments in any form — neither // line comments nor /* block */ comments — and standard parsers reject them with an "Unexpected token '/'" error. If you need annotations, use a dedicated field such as "_comment", keep documentation in a separate file, or switch to a superset like JSONC or JSON5 that your specific tool supports (VS Code settings.json and tsconfig.json use JSONC). Strip all comments before feeding the data to a standard JSON.parse.

Does JSON.parse throw an error on duplicate keys?

No. JSON.parse in JavaScript silently accepts duplicate property names and keeps the last value, so {"id": 1, "id": 2} parses to {"id": 2} with no warning. The JSON spec says names SHOULD be unique but does not require parsers to reject duplicates, and different languages disagree — some keep the first value, some the last, some raise an error. Because the behavior is undefined across platforms, duplicate keys are a real correctness and security risk; validate untrusted input explicitly rather than trusting the parser to catch them.

Why does my JSON fail with 'Unexpected end of JSON input'?

That error means the parser reached the end of the text while still waiting for a closing bracket, brace, or quote — the structure is unbalanced. It is almost always a missing } or ] (or an unterminated string) somewhere above. Pretty-print the JSON so the indentation makes the open structures visible, use your editor's bracket-matching to find the unpaired opener, and add the missing closer. An empty string or a truncated download (a network response cut short) produces the same message.

What is a BOM and how does it break JSON parsing?

A byte-order mark (BOM) is an invisible character (U+FEFF) that some editors and Windows tools add to the very start of a UTF-8 file. RFC 8259 says JSON must not be transmitted with a BOM, and JavaScript's JSON.parse throws "Unexpected token" on a leading BOM even though the visible text looks perfect. Save the file as "UTF-8 without BOM," or strip the leading U+FEFF in code before parsing. A BOM is a classic cause of a JSON error that disappears when you retype the first line by hand.

Can JSON have unescaped newlines or tabs inside a string?

No. Literal control characters (raw newlines, tabs, carriage returns, and other characters below U+0020) are not allowed inside a JSON string and must be written as escape sequences: \n for newline, \t for tab, \r for carriage return. Pasting multi-line text directly into a string value is a frequent cause of "Bad control character in string literal" errors. Let a JSON library serialize the value with JSON.stringify so the escaping is handled for you instead of building strings by hand.

jsondebuggingsyntax errorstroubleshootingweb development