Skip to main content
← Back to Blog
Utilities

JSON Validation Tips: How to Debug and Fix Common JSON Errors Fast

Advertisement

Every developer has been there: you paste a JSON payload into a parser, hit enter, and get an unhelpful error message like "Unexpected token at position 1847." Finding and fixing JSON errors can be a frustrating experience, especially when working with large files or unfamiliar data. The good news is that most JSON errors fall into a handful of common categories, and once you learn to recognize them, you can fix them in seconds. This guide covers the most frequent JSON validation errors, explains why they happen, and shows you how to debug them quickly using the right tools and techniques.

The Most Common JSON Errors

Despite JSON's apparent simplicity — it has only a few data types and a straightforward syntax — it enforces strict rules that trip up even experienced developers. The rules are stricter than JavaScript object literal syntax, which is where most of the confusion originates. Here are the errors you will encounter most often.

Trailing Commas

This is by far the most common JSON error. In JavaScript, trailing commas after the last item in an array or object are perfectly valid (and many code style guides encourage them for cleaner diffs). In JSON, they are a syntax error. A trailing comma tells the parser to expect another element, and when it encounters the closing bracket instead, it fails.

Invalid: {"name": "Alice", "age": 30,} — the comma after 30 is invalid in JSON.

Valid: {"name": "Alice", "age": 30} — remove the trailing comma.

When you encounter a “trailing comma” error, search for commas immediately before closing braces { } or brackets [ ] and remove them. In most code editors, you can use a regular expression search for ,\s*[}\]] to find all trailing commas in a file at once.

Unquoted Keys

In JavaScript object literals, keys can be written without quotes if they are valid identifiers: {name: "Alice"} works fine in JavaScript. In JSON, all keys must be double-quoted: {"name": "Alice"}. Forgetting to quote keys is especially common when writing JSON by hand or when converting JavaScript objects to JSON manually.

This error often appears when developers copy configuration from a JavaScript file into a JSON configuration file, or when they write JSON in a code editor that applies JavaScript syntax highlighting instead of JSON syntax highlighting. Always make sure your editor is set to treat the file as JSON, not JavaScript, so you get the correct syntax checking.

Single Quotes Instead of Double Quotes

JSON requires double quotes for all strings and keys. Single quotes are not valid in JSON, even though they are widely used in JavaScript. An error like {'name': 'Alice'} will fail to parse because of the single quotes. The fix is straightforward: replace all single quotes with double quotes. However, be careful when doing a global find-and-replace — if your string values contain apostrophes (like "it's"), you need to make sure the replacement does not break those.

Comments in JSON

Standard JSON does not support comments of any kind — no single-line comments with // and no block comments with /* */. This is a deliberate design decision by Douglas Crockford, the creator of JSON, who wanted the format to be as simple as possible. If you need comments in your JSON-like files, you are looking for JSONC (JSON with Comments), which is used by VS Code settings, tsconfig.json, and several other tools. But standard JSON parsers will reject any file containing comments.

If you need to add documentation to JSON data, use a dedicated "_comment" key (note the underscore prefix to distinguish it from data keys), or maintain a separate documentation file. Some teams use a "_description" field in their JSON schemas for this purpose.

Unescaped Characters in Strings

JSON strings must properly escape certain characters. The characters that require escaping inside a JSON string are: double quote (\"), backslash (\\), and control characters like newline (\n), tab (\t), carriage return (\r), and others represented as \uXXXX unicode escapes. A literal newline inside a string — a string that spans multiple lines — is invalid in JSON.

This error commonly occurs when copying multi-line text (like addresses, error messages, or formatted content) into a JSON string. The fix is to either use \n escape sequences for newlines or restructure the data so that each line is a separate array element.

BOM (Byte Order Mark) Issues

Some text editors, especially on Windows, prepend a Byte Order Mark (BOM) to UTF-8 files. The BOM is the three-byte sequence EF BB BF at the beginning of the file, which is invisible in most editors but causes JSON parsers to fail because they encounter these bytes before the opening brace. If you get an error at position 0 or a "BOM detected" error, re-save the file without BOM encoding. Most modern editors have a "Save without BOM" or "UTF-8 without BOM" option in the encoding settings.

Debugging Strategies

When you encounter a JSON parse error, the error message usually includes a character position. This position is your starting point for debugging. Open the file in an editor that shows column numbers (most code editors do), navigate to the specified position, and examine the surrounding characters. The error is typically at or just before the reported position.

If the error message is unhelpful (which is common), try a binary search approach: paste the first half of your JSON into a validator. If it parses successfully, the error is in the second half. If it fails, the error is in the first half. Repeat this process to narrow down the error location. This technique is especially useful for very large JSON files where visually scanning for errors is impractical.

Another effective strategy is to use a JSON formatter that highlights the exact location of errors. The JSON formatter and validator on KnowKit processes your data locally in the browser, provides clear error messages with line and column numbers, and formats the output with proper indentation — all without sending your data to any server.

JSON vs JSONC: When to Use Each

JSONC (JSON with Comments) extends standard JSON by allowing both single-line (//) and multi-line (/* */) comments, as well as trailing commas. It is not a separate standard but a convention adopted by tools like VS Code, TypeScript, and several build systems. If you are working with tsconfig.json, .eslintrc.json (in some setups), or VS Code settings files, you are likely using JSONC whether you realize it or not.

The important thing is to know which format your tool expects. Sending JSONC to a standard JSON parser will fail, and stripping comments from JSONC before passing it to a JSON parser is an extra step you need to account for. If you frequently work with JSONC, consider using an editor or tool that natively supports the format.

Validating API Responses

One of the most common scenarios for JSON validation is debugging API responses. When an API returns an error, the response body is often JSON — but sometimes it is HTML (server error pages), XML, or plain text. If your code tries to parse a non-JSON response as JSON, it will fail with a confusing error. Before parsing any API response, verify that the Content-Type header is application/json.

When debugging API issues, tools like a JWT decoder can help you inspect the contents of authentication tokens that are often embedded in JSON responses. And if your API uses Base64-encoded data within JSON payloads, a Base64 decoder can help you decode those values for inspection. Understanding the full structure of your API data — including encoded fields — makes debugging much faster.

Handling Large JSON Files

Large JSON files present unique challenges. Files that are tens or hundreds of megabytes in size can overwhelm browser-based validators and editors. If you need to validate or format a very large JSON file, consider these approaches.

First, check the file size before trying to open it in a browser tool. Most browser-based JSON formatters handle files up to about 50 MB comfortably, but performance degrades beyond that. For larger files, use a command-line tool like jq, which streams the input and uses constant memory regardless of file size. The command jq empty your-file.json validates the file without producing any output — it simply exits with code 0 if the JSON is valid or code 1 if it is not.

Second, if you need to find a specific error in a large file, use a streaming JSON parser that can pinpoint the exact location of the error without loading the entire file into memory. Tools like jsonlint (Node.js) or python -m json.tool can handle moderately large files and provide useful error messages.

URL Encoding in JSON Values

JSON strings often contain URLs, and URLs frequently contain characters that need special handling. In JSON, forward slashes (/) can optionally be escaped as \/, though this is not required. More importantly, URLs often contain query parameters with special characters (ampersands, equals signs, percent signs) that need to be properly encoded. If you are constructing URLs inside JSON, make sure the URL components are properly encoded. A URL parser tool can help you decompose and verify URLs before embedding them in JSON data.

Prevention: Writing Valid JSON the First Time

The best way to fix JSON errors is to avoid creating them in the first place. If you are generating JSON programmatically (which you should be whenever possible), use your language's built-in JSON serialization functions rather than concatenating strings. In JavaScript, use JSON.stringify(); in Python, use json.dumps(); in Go, use json.Marshal(). These functions produce valid JSON by construction and handle escaping, quoting, and formatting automatically.

If you must write JSON by hand (for configuration files, quick tests, or documentation), use an editor with real-time JSON validation. VS Code, for example, highlights JSON errors as you type when the file language is set to JSON. Many online editors also provide real-time validation. The key is to catch errors immediately rather than discovering them when you try to parse the file later.

Finally, consider using JSON Schema for critical data formats. A JSON Schema defines the expected structure, types, and constraints of your JSON data, and a schema validator can catch errors that a basic syntax validator cannot — for example, a missing required field, a string where a number is expected, or a value outside the allowed range. While JSON Schema has a learning curve, it provides a level of validation that is impossible to achieve with syntax checking alone.

Related Tools

Advertisement