Back to blog

Fix Invalid JSON: Common Errors & Solutions

Introduction

A JSON parse error can block an API call, crash a configuration loader, or break a build pipeline in seconds. The frustrating part is that even a single misplaced comma or a wrong quote character is enough to make an entire JSON document invalid.

This guide documents the 10 most common reasons JSON is rejected by parsers, with a broken example, a corrected version, and an explanation for each. It also covers a practical troubleshooting process for when you cannot immediately spot the problem.

For hands-on practice, use the JSON Validator, which includes 20 verified JSON error examples. Each example can be loaded into the validator, copied in invalid or corrected form, and compared without sending data to a server.


What Does "Invalid JSON" Mean?

JSON (JavaScript Object Notation) follows a strict specification defined by RFC 8259. Unlike JavaScript, which tolerates trailing commas, unquoted keys, and single quotes, JSON parsers follow the spec exactly and reject anything that deviates from it.

When a parser encounters a character it does not expect, it throws an error — commonly phrased as:

  • SyntaxError: Unexpected token (JavaScript)
  • json.decoder.JSONDecodeError (Python)
  • com.fasterxml.jackson.core.JsonParseException (Java)
  • Newtonsoft.Json.JsonReaderException (.NET)

The error message almost always includes a character position or line number. That position is where the parser gave up — not necessarily where the original mistake is, since a missing comma on line 3 can make the parser fail on line 4.


1. Missing Commas

Every key-value pair in an object, and every item in an array, must be separated by a comma — except the last one.

Invalid:

{
  "name": "Alice"
  "age": 30
}

Valid:

{
  "name": "Alice",
  "age": 30
}

The parser reads "Alice" and expects either a , or } next. Finding "age" instead causes an immediate parse error. Missing commas are easy to introduce when copying or hand-editing JSON, especially in multi-line objects.


2. Using Single Quotes Instead of Double Quotes

JSON requires double quotes (") around all strings — both property names and string values. Single quotes (') are not valid JSON.

Invalid:

{
  'name': 'Alice'
}

Valid:

{
  "name": "Alice"
}

JavaScript developers are particularly prone to this error because JavaScript objects accept both quote styles. JSON does not. If your editor or terminal is producing JSON with single quotes, the source is usually a JavaScript object being serialized incorrectly.


3. Trailing Commas

A trailing comma is a comma after the last item in an object or array. Modern JavaScript allows this, but JSON does not.

Invalid:

{
  "name": "Alice",
  "role": "admin",
}

Valid:

{
  "name": "Alice",
  "role": "admin"
}

Trailing commas are one of the most common JSON errors because many code editors and linters normalize them in JavaScript files, making it easy to copy JSON from a JS codebase and forget that the JSON spec prohibits them.

The same rule applies to arrays:

Invalid:

["apple", "banana", "cherry",]

Valid:

["apple", "banana", "cherry"]

4. Missing or Mismatched Brackets

Every opening brace { must have a matching closing brace }, and every opening bracket [ must have a matching closing bracket ]. Incorrect nesting or a missing delimiter makes the entire document invalid.

Invalid (unclosed object):

{
  "user": {
    "name": "Alice",
    "age": 30
}

Valid:

{
  "user": {
    "name": "Alice",
    "age": 30
  }
}

Invalid (mixed bracket types):

{
  "tags": ["admin", "editor")
}

Valid:

{
  "tags": ["admin", "editor"]
}

Deep nesting makes bracket matching errors harder to spot by eye. A validator or editor with bracket-matching highlighting is the fastest way to find them.


5. Unquoted Property Names

In JSON, every object key must be a double-quoted string. In JavaScript object literals, unquoted and single-quoted keys are perfectly fine — but not in JSON.

Invalid:

{
  name: "Alice",
  age: 30
}

Valid:

{
  "name": "Alice",
  "age": 30
}

This error frequently appears when developers paste a JavaScript object directly into a JSON context — for example, into a fetch request body or a config file — without converting it to valid JSON first.


6. Invalid Boolean or Null Values

JSON supports exactly three literal values: true, false, and null — all lowercase. Any other casing or alternative spelling is invalid.

Invalid:

{
  "active": True,
  "deleted": False,
  "value": None,
  "count": NULL
}

Valid:

{
  "active": true,
  "deleted": false,
  "value": null,
  "count": null
}

The True/False/None pattern comes from Python, where these are the correct boolean and null literals. When serializing Python objects to JSON, always use json.dumps() rather than str() — json.dumps() converts them to the correct JSON representation automatically.

Note also that undefined, NaN, and Infinity are not valid JSON values and will be stripped or rejected when serializing from JavaScript.


7. Invalid Escape Characters

Inside a JSON string, certain characters must be escaped with a backslash. The valid JSON escape sequences are:

SequenceMeaning
\"double quote
\\backslash
\/forward slash (optional)
\nnewline
\rcarriage return
\ttab
\bbackspace
\fform feed
\uXXXXUnicode code point

Any other \x sequence is invalid.

Invalid (unescaped backslash in Windows path):

{
  "path": "C:\Users\alice\documents"
}

Valid:

{
  "path": "C:\\Users\\alice\\documents"
}

Invalid (raw newline inside a string):

{
  "message": "Hello
World"
}

Valid:

{
  "message": "Hello\nWorld"
}

Literal newlines and unescaped backslashes inside string values are among the most common sources of JSON syntax errors when the JSON is built by hand or via string concatenation.


8. Comments Inside JSON

Standard JSON does not support comments of any kind. Not // single-line comments. Not /* */ block comments.

Invalid:

{
  "name": "Alice",
  "age": 30
}

If you need comments in JSON-like config files, consider:

  • JSONC — a JSON superset used by VS Code settings (settings.json) and TypeScript config (tsconfig.json) that allows // comments.
  • JSON5 — a more permissive JSON superset that allows comments, trailing commas, and unquoted keys.
  • YAML — supports comments natively with #.

For standard JSON consumed by APIs, databases, or parsers, there is no comment support. Remove comments before passing JSON to a parser.


9. Incorrect JSON Nesting

A common structural error is placing a value at the wrong level of nesting — for example, a second top-level object key placed outside any enclosing object, or an array item that contains a bare key-value pair.

Invalid (two top-level objects — JSON allows only one root value):

{
  "name": "Alice"
}
{
  "role": "admin"
}

Valid (merge them into one object):

{
  "name": "Alice",
  "role": "admin"
}

Invalid (key-value pair placed directly inside an array):

["apple", "role": "admin", "banana"]

Valid (use an array of objects when grouping is needed):

[
  { "fruit": "apple" },
  { "role": "admin" },
  { "fruit": "banana" }
]

JSON arrays hold values. JSON objects hold key-value pairs. These two structures cannot be mixed at the same nesting level.


10. Valid JSON but Wrong Data Structure

Syntactically valid JSON is not the same as structurally correct JSON for a given application or API. A document can pass every JSON syntax check and still be rejected by the consuming service because the shape of the data is wrong.

Example — an API expects an array of user objects:

[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]

But you sent a single object:

{ "id": 1, "name": "Alice" }

The single object is syntactically valid JSON. The parser accepts it. But application code that iterates over an expected array will throw a runtime error.

Other examples of structurally incorrect but syntactically valid JSON:

  • Sending a string where a number is expected: "age": "30" vs "age": 30
  • Using the wrong field name: "userName" vs "username"
  • Omitting a required field: { "name": "Alice" } when email is required

For structural validation, you need a JSON Schema validator — not just a syntax checker. JSON Schema defines the expected shape of a document (types, required fields, allowed values) and reports structural errors that a JSON syntax validator would not catch.


How to Find the Exact JSON Error

When you cannot spot the problem by reading the JSON, follow this process:

  1. Validate the JSON first. Paste it into a JSON Validator — it identifies the exact line and character of the error rather than making you scan manually.

  2. Check the error position. Parser error messages report a byte offset or line/character number. Go directly to that position. The mistake is usually one token before the reported position.

  3. Check commas. Scan for trailing commas (after the last item) and missing commas (between items). These are the most common cause.

  4. Check quotation marks. Confirm all string values and property names use double quotes. Search for ' characters in the JSON.

  5. Check brackets. Count opening and closing { / } and [ / ]. A good editor will highlight mismatched pairs.

  6. Check escape sequences. Look for bare backslashes, literal newlines inside strings, or characters like \x that are not valid JSON escape sequences.

  7. Check data types. Verify that true, false, and null are lowercase, and that numbers are not wrapped in quotes unless they are intentionally strings.

  8. Revalidate after each fix. Fix one error at a time and revalidate. A single missing comma can cause a cascade of apparent errors further in the document.

Note: the exact wording of parser error messages differs between programming languages and JSON libraries. SyntaxError in JavaScript, JSONDecodeError in Python, and JsonParseException in Java all describe the same kind of underlying problem, but the error text and reported position may differ.


How to Validate JSON

The fastest way to check for syntax errors is to paste your JSON into a browser-based JSON Validator. A validator confirms whether the document is syntactically correct and highlights the specific line and character where the error occurs — no installation required.

In code, use the native JSON parser for your language and wrap it in error handling:

JavaScript:

try {
  const data = JSON.parse(jsonString);
} catch (err) {
  console.error("Invalid JSON:", err.message);
}

Python:

import json

try:
    data = json.loads(json_string)
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")

Go:

var data interface{}
if err := json.Unmarshal([]byte(jsonString), &data); err != nil {
    log.Printf("Invalid JSON: %v", err)
}

How to Format JSON

Once you have confirmed a JSON document is valid, formatting (pretty-printing) it makes deeply nested structures significantly easier to read and debug. Proper indentation reveals nesting problems that are invisible in minified JSON.

Use the JSON Formatter to instantly pretty-print or minify any valid JSON document in your browser. It also catches syntax errors before formatting, so it doubles as a quick validator.

In JavaScript, JSON.stringify(data, null, 2) produces indented output with 2-space indentation. JSON.stringify(data) produces minified output.


JSON Troubleshooting Checklist

When your JSON is rejected, work through this list:

  • All strings (keys and values) use double quotes — not single quotes
  • No trailing comma after the last item in any object or array
  • No missing comma between items
  • Every { has a matching } and every [ has a matching ]
  • Brackets are not mixed ([ closed with } or { closed with ])
  • All booleans are true or false (lowercase)
  • Null values are null (lowercase), not None, nil, or NULL
  • No undefined, NaN, or Infinity values
  • No raw newlines inside string values — use \n instead
  • No unescaped backslashes inside strings — use \\
  • No comments (// or /* */)
  • Data structure matches what the consuming application expects

Frequently Asked Questions

Why is my JSON invalid?

The most common causes are: trailing commas, single quotes instead of double quotes, missing commas between properties, unquoted property names, and comments inside the JSON. Pasting into a JSON Validator will identify the exact location of the problem instantly.

Why does JSON require double quotes?

The JSON specification (RFC 8259) defines double quotes as the only valid string delimiter. Single quotes are valid in JavaScript but are not part of the JSON spec. Every JSON parser in every language follows RFC 8259 strictly, so single-quoted strings are universally rejected.

Can JSON contain comments?

No. Standard JSON does not support // or /* */ comments. The original creator of JSON, Douglas Crockford, intentionally excluded comments to prevent JSON from being used as a configuration format where comments would accumulate. If you need comments in config files, use JSONC, JSON5, or YAML.

How do I find where JSON is broken?

Use a JSON Validator — it identifies the exact line and character of the error. If you are debugging in code, catch the parser exception: it includes a position offset you can use to locate the problem character in your JSON string.

What is the difference between JSON validation and formatting?

Validation checks whether a JSON string conforms to the JSON syntax specification and reports errors if not. Formatting takes valid JSON and re-indents it with consistent whitespace to make it easier to read. Formatting will not work on invalid JSON — fix all syntax errors first.


Related Guides and Tools

  • What is JSON? A Complete Developer's Guide — JSON syntax rules, all six data types, and common mistakes explained from first principles.
  • JSON vs XML — When to choose JSON over XML (and vice versa), with syntax comparison and practical use-case guidance.
  • JSON Formatter — Format and beautify any valid JSON string in your browser.
  • JSON Validator — Paste JSON to find the exact line and character of syntax errors instantly.