Skip to content
UtilHQ
developer

Common JSON Syntax Errors and How to Fix Them

Fix JSON syntax errors fast with this developer guide. Learn the top 5 JSON parsing errors, before/after examples, and debugging techniques to validate JSON instantly.

By UtilHQ Team
Ad Space

Working with JSON is a daily task for developers, but even experienced programmers encounter syntax errors that break parsing. One misplaced comma or quote can halt your entire application. This guide breaks down the five most common JSON syntax errors and shows you exactly how to fix them.

The Quick Answer

Here are the top 5 JSON syntax errors you’ll encounter and their instant fixes:

  1. Trailing commas - Remove the comma after the last item in objects or arrays
  2. Single quotes - Replace all single quotes (') with double quotes (")
  3. Unquoted keys - Wrap all object keys in double quotes
  4. Comments - Remove all // or /* */ comments (JSON doesn’t support them)
  5. Missing commas - Add commas between array items and object properties

These five errors account for roughly 80% of all JSON parsing failures. Master them, and you’ll save hours of debugging time.

Error Breakdown with Examples

1. Trailing Commas

JSON spec forbids commas after the last element. JavaScript is forgiving, but JSON parsers are strict.

Before (Invalid):

{
  "name": "John",
  "age": 30,
  "email": "john@example.com",
}

After (Valid):

{
  "name": "John",
  "age": 30,
  "email": "john@example.com"
}

Why it breaks: The JSON specification explicitly states that commas separate values. A trailing comma implies another value is coming, but none exists, which confuses the parser.

Quick fix: Remove the comma after "email".

2. Single Quotes

JSON requires double quotes for strings. Single quotes are invalid.

Before (Invalid):

{
  'name': 'John',
  'age': 30
}

After (Valid):

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

Why it breaks: The JSON standard is derived from JavaScript object literal syntax but is more restrictive. Only double quotes are allowed for string delimiters.

Quick fix: Find and replace all ' with " in your JSON string.

3. Unquoted Keys

Object keys must be quoted strings in JSON, unlike JavaScript where they can be unquoted.

Before (Invalid):

{
  name: "John",
  age: 30,
  isActive: true
}

After (Valid):

{
  "name": "John",
  "age": 30,
  "isActive": true
}

Why it breaks: While JavaScript allows unquoted keys in object literals, JSON requires all keys to be strings wrapped in double quotes. This eliminates ambiguity.

Quick fix: Wrap every key in double quotes.

4. Comments

JSON doesn’t support comments. Any // or /* */ will cause parsing errors.

Before (Invalid):

{
  // User information
  "name": "John",
  "age": 30 /* years old */
}

After (Valid):

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

Why it breaks: JSON is a data format, not a programming language. Comments would require additional parsing logic and would complicate machine-to-machine communication.

Quick fix: Remove all comments. If documentation is needed, add a "_comment" key with your notes as the value (though this is non-standard).

5. Missing Commas

Properties and array elements must be separated by commas.

Before (Invalid):

{
  "name": "John"
  "age": 30
  "hobbies": ["reading" "coding" "gaming"]
}

After (Valid):

{
  "name": "John",
  "age": 30,
  "hobbies": ["reading", "coding", "gaming"]
}

Why it breaks: Commas are required separators. Without them, the parser can’t determine where one property ends and another begins.

Quick fix: Add commas between all properties and array elements, but remember rule #1: no trailing commas.

JSON Syntax Reference Chart

ElementRuleExample
StringsDouble quotes only"hello" ✓ / 'hello'
KeysMust be quoted"name" ✓ / name
NumbersNo quotes42 ✓ / "42" is string
BooleansLowercasetrue ✓ / True
NullLowercasenull ✓ / NULL
ArraysSquare brackets[1, 2, 3]
ObjectsCurly braces{"key": "value"}
CommasBetween items, not after last[1, 2] ✓ / [1, 2,]
CommentsNot allowed// comment

Debugging Tips - How to Find the Error Location

1. Use Error Messages

Most JSON parsers provide error locations. In JavaScript:

try {
  JSON.parse(jsonString);
} catch (error) {
  console.error(error.message);
  // "Unexpected token } in JSON at position 45"
}

The position number tells you exactly where the parser failed, so count 45 characters from the start to find the problematic character.

2. Binary Search Method

For large JSON files without clear error messages:

  1. Comment out half the content
  2. Try parsing
  3. If it works, the error is in the commented half
  4. If it fails, the error is in the uncommented half
  5. Repeat until you isolate the problematic line

3. Visual Inspection Checklist

Scan your JSON for these red flags:

  • ✓ Every opening { has a closing }
  • ✓ Every opening [ has a closing ]
  • ✓ All strings use double quotes
  • ✓ All keys are quoted
  • ✓ Commas between items (but not after the last one)
  • ✓ No comments
  • ✓ Numbers don’t have quotes (unless they’re meant to be strings)

4. Use Online Validators

When debugging locally fails, paste your JSON into an online validator. Tools like JSONLint or our JSON Formatter highlight errors with line numbers and specific suggestions.

Pro Tips for JSON Excellence

1. Use JSON Linters

Integrate JSON validation into your development workflow:

VS Code: Install the “JSON Tools” extension for real-time validation and formatting.

ESLint: Use eslint-plugin-json to catch errors before runtime:

npm install --save-dev eslint-plugin-json

Command line: Use jsonlint for CI/CD pipelines:

npm install -g jsonlint
jsonlint -q config.json

2. Schema Validation with JSON Schema

Beyond syntax, validate structure and data types:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "age": {"type": "number", "minimum": 0},
    "email": {"type": "string", "format": "email"}
  },
  "required": ["name", "email"]
}

Libraries like Ajv (JavaScript) or jsonschema (Python) enforce these rules at runtime, catching not just syntax errors but also type mismatches and missing required fields.

3. Pretty Print for Readability

Minified JSON is impossible to debug. Always format during development:

JavaScript:

JSON.stringify(data, null, 2); // 2-space indentation

Python:

import json
json.dumps(data, indent=2)

Command line (jq):

cat config.json | jq '.'

4. Use TypeScript or JSON Schema for Type Safety

TypeScript interfaces catch type errors before runtime:

interface User {
  name: string;
  age: number;
  email: string;
}

const user: User = JSON.parse(jsonString);

If the parsed JSON doesn’t match the interface, TypeScript throws a compile-time error.

5. Automate Formatting

Set up pre-commit hooks to format JSON automatically:

Using Prettier:

npm install --save-dev prettier
npx prettier --write "**/*.json"

Add to .prettierrc:

{
  "trailingComma": "none",
  "tabWidth": 2,
  "semi": false
}

Common Mistakes Beyond Syntax

1. Assuming JavaScript === JSON

JavaScript object literals allow:

  • Unquoted keys
  • Single quotes
  • Trailing commas
  • Functions and undefined
  • Comments

JSON allows none of these. JSON is a strict subset of JavaScript syntax.

2. Encoding Issues

JSON must be UTF-8 encoded. Curly quotes (" instead of ") or special characters from rich text editors break parsing.

Fix: Use a plain text editor and ensure UTF-8 encoding.

3. NaN and Infinity

JavaScript has NaN and Infinity, but JSON doesn’t. Use null or strings instead:

// Invalid JSON
{"value": NaN}

// Valid alternatives
{"value": null}
{"value": "NaN"}

4. Circular References

JSON can’t represent circular references. This fails:

const obj = {};
obj.self = obj;
JSON.stringify(obj); // TypeError: Converting circular structure to JSON

Fix: Break the circular reference, or use a library like flatted that handles cycles.

5. Date Objects

Dates aren’t native JSON types:

// This stringifies as ISO 8601
JSON.stringify({date: new Date()});
// {"date":"2024-12-31T10:30:00.000Z"}

// Parse it back
const obj = JSON.parse(jsonString);
obj.date = new Date(obj.date); // Convert string back to Date

Testing Your JSON

Create a simple validation function for your projects:

function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

// Usage
if (isValidJSON(userInput)) {
  const data = JSON.parse(userInput);
  // Process data
} else {
  console.error('Invalid JSON provided');
}

For production systems, add detailed error logging:

function validateJSON(str) {
  try {
    return { valid: true, data: JSON.parse(str) };
  } catch (error) {
    return {
      valid: false,
      error: error.message,
      position: error.message.match(/position (\d+)/)?.[1]
    };
  }
}

Real-World Debugging Example

Let’s debug a realistic error:

{
  "users": [
    {
      "name": "Alice",
      "age": 28,
      "roles": ['admin', 'editor']
    },
    {
      "name": "Bob"
      "age": 35,
      "roles": ["viewer"],
    }
  ]
}

Errors found:

  1. Line 5: Single quotes around 'admin' and 'editor' (should be double quotes)
  2. Line 7: Missing comma after "name": "Bob"
  3. Line 9: Trailing comma after ["viewer"]

Fixed version:

{
  "users": [
    {
      "name": "Alice",
      "age": 28,
      "roles": ["admin", "editor"]
    },
    {
      "name": "Bob",
      "age": 35,
      "roles": ["viewer"]
    }
  ]
}

When to Use a JSON Formatter

Manual debugging works for small files, but for large configuration files, API responses, or nested data structures, use our JSON Formatter to:

  • Instantly validate syntax
  • Auto-format with proper indentation
  • Highlight errors with line numbers
  • Minify for production
  • Copy formatted output with one click

The tool catches all five common errors instantly and provides a clean, readable format for complex JSON structures. It’s especially handy when working with API responses that return minified JSON. Simply paste it in and get beautifully formatted, valid JSON out.

Frequently Asked Questions

What is the difference between JSON and JavaScript objects?

JSON is a strict subset of JavaScript object syntax. While JavaScript allows unquoted keys, single quotes, trailing commas, functions, undefined, and comments, JSON forbids all of these. JSON requires double-quoted keys and string values, no trailing commas, and only supports primitives (strings, numbers, booleans, null), arrays, and objects. Think of JSON as the wire format for data interchange, while JavaScript objects are a programming construct.

How do I find where the JSON error is in a large file?

Use the error message’s position number. JSON.parse() throws errors like “Unexpected token } in JSON at position 45.” Count 45 characters from the start to locate the problem. For files without clear error messages, use the binary search method: comment out half the content, try parsing, and repeat on the half that contains the error. Online validators like our JSON Formatter tool highlight errors with exact line numbers and suggestions.

Can I add comments to JSON files?

No, JSON doesn’t officially support comments. Any // or /* */ will cause parsing errors. If you need documentation, a common workaround is adding a non-standard key like "_comment": "your note here", though this isn’t part of the JSON specification and adds to file size. For configuration files where comments are essential, consider using JSON5, YAML, or TOML instead, which support comments natively.

Why does my JSON work in JavaScript but fail validation?

JavaScript is forgiving and allows syntax that violates the JSON specification. Your browser might successfully parse JavaScript object literals with single quotes ('key'), unquoted keys ({name: "value"}), trailing commas ([1, 2,]), or even undefined values. However, strict JSON parsers reject all of these. When sharing data between systems or using APIs, you must follow the strict JSON rules: double quotes, no trailing commas, quoted keys.

How do I validate JSON before sending it to an API?

Use JSON.parse() in a try/catch block to test locally before sending. For example: try { JSON.parse(jsonString); } catch (error) { console.error(error.message); }. For production systems, integrate JSON schema validation using libraries like Ajv (JavaScript) or jsonschema (Python) to catch not just syntax errors but also type mismatches and missing required fields. Our JSON Formatter tool also provides instant browser-based validation.

Final Checklist

Before deploying JSON to production:

  • All strings use double quotes
  • All object keys are quoted
  • No trailing commas
  • No comments
  • Proper commas between all items
  • Balanced brackets {} and []
  • Valid escape sequences in strings
  • UTF-8 encoding
  • No undefined, NaN, or Infinity
  • Tested with JSON.parse() or online validator

Master these rules, and JSON errors become a thing of the past. When in doubt, paste into a validator. It’s faster than hunting for a misplaced comma.

Related Calculators

Share this article

Have suggestions for this article?