jsonvalidationsyntax-errorsdebuggingtutorial

How to Validate JSON: Common Errors and How to Fix Them

JSON Tools Team
9 min read

JSON has become the default data interchange format for the modern web. APIs return it, configuration files use it, databases store it, and front-end applications consume it constantly. Yet despite its simplicity, JSON has strict syntax rules — and a single misplaced character can break an entire data pipeline.

The good news is that JSON validation errors are almost always easy to fix once you know what to look for. In this article, we will cover the most common JSON syntax errors developers encounter, explain exactly why each one occurs, and show you how to fix them. By the end, you will be able to diagnose and resolve JSON issues in seconds rather than minutes.

What Is JSON Validation?

JSON validation is the process of checking whether a string conforms to the JSON specification defined in RFC 8259. A valid JSON document must follow a precise set of rules about data types, quoting, nesting, and punctuation. If any rule is violated, the document is invalid — and any parser attempting to read it will throw an error.

Validation answers a simple yes-or-no question: Is this string well-formed JSON? It does not tell you whether the data makes logical sense for your application (that is schema validation, a separate concern). Syntax validation just confirms that the document can be parsed at all.

You can validate JSON programmatically using JSON.parse() in JavaScript or equivalent functions in other languages. But for day-to-day debugging, an online JSON Validator is faster because it highlights the exact location of the error and explains what went wrong.

The 8 Most Common JSON Syntax Errors

1. Trailing Commas

This is the single most frequent JSON error. JavaScript allows trailing commas in arrays and objects, but JSON does not. If you copy an object literal from your JavaScript code into a JSON file, trailing commas will silently tag along.

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

The comma after "Portland" is illegal. The fix is simply to remove it:

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

Tip: This error is especially common when you delete the last item in a list and forget to remove the comma from the new last item.

2. Missing Commas Between Elements

The opposite problem: forgetting to add a comma between two key-value pairs or array elements.

{
  "firstName": "Bob"
  "lastName": "Smith"
}

The parser expects either a comma or a closing brace after "Bob", but instead it finds another key. Add the missing comma:

{
  "firstName": "Bob",
  "lastName": "Smith"
}

3. Unquoted or Single-Quoted Keys

In JavaScript, object keys can be unquoted if they are valid identifiers, and strings can use single quotes. JSON requires double quotes for both keys and string values — no exceptions.

{
  name: 'Alice',
  age: 30
}

The corrected version:

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

If you frequently work with data that uses single quotes — for example, Python dictionaries printed with str() instead of json.dumps() — you will encounter this error often. A quick find-and-replace of single quotes to double quotes usually resolves it, but be careful with apostrophes inside string values.

4. Unescaped Special Characters in Strings

JSON strings must escape certain characters with a backslash. The most common culprits are:

  • Double quotes inside strings: use \"
  • Backslashes: use \\
  • Newlines: use \n
  • Tabs: use \t

Here is an example of the problem:

{
  "message": "She said "hello" to everyone",
  "path": "C:\Users\Alice\Documents"
}

The corrected version escapes the inner quotes and backslashes:

{
  "message": "She said \"hello\" to everyone",
  "path": "C:\\Users\\Alice\\Documents"
}

If you are dealing with complex strings that contain many special characters, our JSON Escape tool can handle the escaping automatically.

5. Using Comments

Developers coming from JSONC (used by VS Code's settings.json) or JSON5 often include comments in standard JSON. The JSON specification does not allow comments of any kind.

{
  // Database configuration
  "host": "localhost",
  "port": 5432, /* default PostgreSQL port */
  "name": "myapp_db"
}

To fix this, remove all comments. If you need to document your JSON configuration, consider using a "_comment" key as a convention (though this adds data to the payload) or maintain a separate documentation file.

{
  "_comment": "Database configuration",
  "host": "localhost",
  "port": 5432,
  "name": "myapp_db"
}

6. Wrong Value Types

JSON supports exactly six value types: strings, numbers, booleans (true/false), null, objects, and arrays. Common mistakes include:

  • Using undefined (not valid in JSON — use null instead)
  • Using NaN or Infinity (not valid — use null or a string representation)
  • Wrapping numbers in quotes when they should be numeric: "age": "30" vs. "age": 30
  • Using True/False (Python style) instead of lowercase true/false

7. Mismatched Brackets and Braces

Every opening { must have a closing }, and every [ must have a closing ]. In deeply nested structures, it is easy to lose track.

{
  "users": [
    {
      "name": "Alice",
      "contacts": [
        { "type": "email", "value": "alice@example.com" }
      ]
    },
    {
      "name": "Bob",
      "contacts": [
        { "type": "phone", "value": "555-0100" }
      ]
  ]
}

Can you spot the error? Bob's object is missing its closing } before the array-closing ]. These errors are much easier to find in formatted JSON than in minified JSON, which is one more reason to always format your JSON before inspecting it.

8. Duplicate Keys

While not strictly a parse error in most implementations (the JSON spec says behavior is undefined for duplicate keys), duplicate keys are a common source of bugs. Most parsers will silently use the last value, which can lead to data loss.

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

In this example, most parsers will set name to "Bob", silently discarding "Alice". A good JSON validator will warn you about duplicates even if the document is technically parseable.

How to Validate JSON Online: Step by Step

  1. Open the validator. Navigate to the JSON Validator tool.
  2. Paste your JSON. Copy the JSON you want to check into the input editor.
  3. Click "Validate". The tool parses your JSON and reports whether it is valid or invalid.
  4. Read the error message. If validation fails, the tool highlights the exact line and character position where the error was detected and describes the problem.
  5. Fix and re-validate. Correct the error and validate again. Repeat until the document passes.

For documents with multiple errors, fix them one at a time starting from the top of the file. A single early error (like a missing comma on line 3) can cause cascading false errors on every subsequent line. Fixing the first error often resolves several others automatically.

Validating JSON Programmatically

In production code, you should always validate JSON before processing it. Here is a robust pattern in JavaScript:

function parseJSON(input) {
  try {
    return { ok: true, data: JSON.parse(input) };
  } catch (err) {
    return { ok: false, error: err.message };
  }
}

// Usage
const result = parseJSON('{"name": "Alice", "age": 30}');
if (result.ok) {
  console.log("Valid JSON:", result.data);
} else {
  console.error("Invalid JSON:", result.error);
}

This pattern wraps JSON.parse() in a try/catch and returns a result object, making it safe to use in data pipelines without crashing on bad input. The error message from the parser usually includes the position of the syntax error, which you can use for debugging or display to users.

Syntax Validation vs. Schema Validation

It is important to distinguish between syntax validation (is this valid JSON?) and schema validation (does this JSON have the structure my application expects?). Syntax validation only checks grammar. Schema validation checks the shape and types of the data.

For example, this JSON is syntactically valid:

{
  "user": {
    "name": 12345,
    "email": true
  }
}

But it is clearly wrong from a business logic perspective: name should be a string, and email should be an email address string, not a boolean. To catch these kinds of errors, you need a schema validation tool like JSON Schema, Zod, or Joi — which operate on top of the already-parsed JSON object.

Best Practices for Avoiding JSON Errors

  • Never hand-write large JSON files. Use a code editor with JSON syntax highlighting and validation built in. VS Code, for example, underlines JSON errors in real time.
  • Generate JSON from code, not string concatenation. Building JSON by concatenating strings is fragile and error-prone. Use JSON.stringify() or your language's equivalent to guarantee valid output.
  • Format before inspecting. Always format your JSON before trying to debug it. Structural errors are nearly invisible in minified JSON.
  • Validate early in your pipeline. Validate JSON at the boundary where it enters your system — API endpoints, file loaders, message queue consumers — rather than deep inside your business logic.
  • Use linting in CI/CD. Add a JSON lint step to your continuous integration pipeline so that malformed JSON configuration files are caught before they reach production.
  • Escape strings properly. When embedding user input or file paths in JSON, always pass them through a proper escaping function. Our JSON Escape tool can help you verify that strings are correctly escaped.

How to Read JSON Parse Error Messages

Different parsers report errors differently, but most include two pieces of information: the position of the error and a description of what went wrong. Here are some common error messages and what they mean:

  • Unexpected token } at position 42 — The parser found a closing brace where it expected a value. Usually caused by a trailing comma or a missing value.
  • Expected double-quoted property name — A key is not wrapped in double quotes, or single quotes were used instead.
  • Unexpected end of JSON input — The JSON string ended before all objects and arrays were closed. Check for mismatched brackets.
  • Unexpected token u in JSON at position 0 — The input is not JSON at all. This often happens when JSON.parse() receives undefined (which starts with "u") instead of a string.

When the error message references a position number, paste your JSON into the JSON Validator to see exactly which line and column the error falls on.

Validate Your JSON Now

Stop guessing where the error is. Paste your JSON into our free online JSON Validator and get instant feedback with precise error locations. It works entirely in your browser — your data stays private and is never sent to a server.

Once your JSON is valid, use the JSON Formatter to pretty-print it for easy reading, or the JSON Escape tool to safely embed strings with special characters.

Conclusion

JSON syntax errors are among the most common — and most frustrating — bugs in web development. But they follow predictable patterns: trailing commas, missing quotes, unescaped characters, mismatched brackets. Once you know the patterns, you can diagnose most JSON errors in seconds just by reading the parser's error message.

Make JSON validation a habit, not an afterthought. Validate at the boundaries of your system, format before debugging, and generate JSON from code rather than string concatenation. These practices will save you hours of debugging and keep your data pipelines running smoothly.