DevToys Web Pro iconDevToys Web ProBlog
Nilai kami:
Cuba sambungan pelayar:
← Back to Blog

JSON Trailing Commas and Comments: Why Your JSON Fails to Parse

10 min read

You copy a JSON configuration from documentation, paste it into your app, and get Unexpected token or SyntaxError. The culprit? A trailing comma after the last array element or a helpful // comment that strict JSON parsers reject. This guide explains why JSON is so strict, where non-standard JSON appears, and how to handle it.

The JSON Specification: Strict by Design

JSON (JavaScript Object Notation) is defined by RFC 8259. It's intentionally minimal with strict rules:

  • No trailing commas: Commas separate elements; a trailing comma implies a missing element
  • No comments: JSON has no comment syntax (//, /* */, or #)
  • Double quotes only: Strings must use ", not '
  • No unquoted keys: Object keys must be quoted strings

Why so strict? Simplicity and interoperability. JSON parsers must produce identical results across all languages and platforms. Allowing flexibility (like JavaScript does) would break this guarantee.

Problem #1: Trailing Commas

Invalid JSON with Trailing Comma

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

Error: Unexpected token } in JSON at position 53

Why it fails: The comma after "active": true signals another property should follow. When the parser encounters }, it expects a key, not the closing brace.

Array with Trailing Comma

{
  "tags": ["dev", "api", "json",]
}

Error: Unexpected token ] in JSON at position 36

Fix: Remove the trailing comma:

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

{
  "tags": ["dev", "api", "json"]
}

Why Trailing Commas Are Common

JavaScript allows trailing commas (since ES5):

const user = {
  name: "Alice",
  age: 30,
  active: true,  // Valid JavaScript
};

const tags = ["dev", "api", "json",];  // Valid JavaScript

Trailing commas make diffs cleaner when adding properties (no need to modify the previous line). Developers accustomed to JavaScript often add them to JSON without realizing JSON doesn't allow it.

Problem #2: Comments in JSON

Invalid JSON with Comments

{
  // User configuration
  "name": "Alice",
  "age": 30,  // Updated on 2026-01-20
  "active": true
}

Error: Unexpected token / in JSON at position 4

Why it fails: JSON has no comment syntax. The // characters are not recognized, causing parsing errors.

Block Comments Also Fail

{
  /* User profile */
  "name": "Alice",
  "age": 30
}

Error: Unexpected token / in JSON at position 4

Fix: Remove all comments:

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

Why Comments Appear in JSON

  1. Documentation examples: Tutorials often add comments for clarity
  2. Configuration files: Developers want to document settings
  3. JavaScript influence: JSON syntax is based on JavaScript, which allows comments

Problem #3: Single Quotes

Invalid JSON with Single Quotes

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

Error: Unexpected token ' in JSON at position 4

Why it fails: JSON requires double quotes (") for strings. Single quotes (') are not valid.

Fix: Use double quotes:

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

Problem #4: Unquoted Keys

Invalid JSON with Unquoted Keys

{
  name: "Alice",
  age: 30
}

Error: Unexpected token n in JSON at position 4

Why it fails: JSON requires object keys to be quoted strings.

Fix: Quote all keys:

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

Where Non-Standard JSON Appears

1. Configuration Files (JSON5, JSONC)

Many tools support JSON5 or JSONC (JSON with Comments) for configuration files:

tsconfig.json
// JSONC - VS Code supports this
{
  // Compiler options
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
  },
  "include": ["src/**/*"],
}

Tools that support JSONC/JSON5:

  • VS Code configuration files (settings.json, tsconfig.json)
  • Babel configuration (.babelrc)
  • ESLint configuration (.eslintrc)
  • Package.json (some fields accept comments via special keys)

Problem: Copying JSONC to a strict JSON context (API, database) causes parsing errors.

2. API Documentation Examples

Documentation often includes comments for clarity:

// Example API request (from docs)
POST /api/users
{
  "name": "Alice",
  "email": "alice@example.com",  // Must be unique
  "role": "admin"  // Options: admin, user, guest
}

// This works in docs but fails in actual API call!

Fix: Strip comments before sending:

{
  "name": "Alice",
  "email": "alice@example.com",
  "role": "admin"
}

3. JavaScript Object Literals

Developers sometimes confuse JavaScript object literals with JSON:

// Valid JavaScript (NOT JSON)
const config = {
  name: "Alice",  // Unquoted key
  tags: ["dev", "api",],  // Trailing comma
  active: true,
};

// If you JSON.stringify() this, it produces valid JSON:
JSON.stringify(config);
// Output: {"name":"Alice","tags":["dev","api"],"active":true}

How to Identify and Fix Non-Standard JSON

Use a JSON Validator

The JSON Formatter and JSON Validator immediately highlight syntax errors:

// Input with errors
{
  "name": "Alice",
  "age": 30,  // Comment
  "tags": ["dev",]  // Trailing comma
}

// Validator output:
// Line 3: Unexpected token / (comments not allowed)
// Line 4: Unexpected token ] (trailing comma)

Remove Comments Programmatically

Use libraries like strip-json-comments (Node.js):

const stripJsonComments = require('strip-json-comments');

const jsonWithComments = `{
  // User config
  "name": "Alice",
  "age": 30  // Updated
}`;

const cleanJson = stripJsonComments(jsonWithComments);
const parsed = JSON.parse(cleanJson);
// Works!

Find Trailing Commas with Regex

Search for commas followed by closing brackets:

// Regex pattern to find trailing commas
/,\s*([\]}])/

// Matches:
"tags": ["dev",]   // ← Trailing comma before ]
"age": 30,}        // ← Trailing comma before }

Use the RegEx Tester to test this pattern against your JSON.

JSON5: Official "Relaxed JSON"

JSON5 is a superset of JSON that allows common JavaScript syntax:

// Valid JSON5
{
  // Comments are allowed
  name: 'Alice',           // Unquoted keys, single quotes
  age: 30,
  tags: ['dev', 'api',],   // Trailing commas
  hexValue: 0xFF,          // Hex numbers
  longString: 'This is a \
    multiline string',
}

When to use JSON5:

  • Configuration files where humans edit JSON
  • When you control both writer and reader (no external APIs)
  • Build tools that support JSON5 (Babel, ESLint, etc.)

When NOT to use JSON5:

  • APIs (most API clients expect strict JSON)
  • Databases (JSON columns expect RFC 8259 JSON)
  • When sharing data with external systems

Common Parsing Error Messages

JavaScript (Node.js, Browser)

// Trailing comma
SyntaxError: Unexpected token } in JSON at position 53

// Comment
SyntaxError: Unexpected token / in JSON at position 4

// Single quotes
SyntaxError: Unexpected token ' in JSON at position 4

// Unquoted keys
SyntaxError: Unexpected token n in JSON at position 4

Python

import json

# Trailing comma
json.loads('{"name": "Alice",}')
# json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes

# Comment
json.loads('{"name": "Alice" // comment}')
# json.decoder.JSONDecodeError: Expecting ',' delimiter

Go

// Trailing comma
err := json.Unmarshal([]byte(`{"name":"Alice",}`), &data)
// invalid character '}' looking for beginning of object key string

// Comment
err := json.Unmarshal([]byte(`{"name":"Alice" // comment}`), &data)
// invalid character '/' looking for beginning of value

Best Practices for JSON

  1. Validate before sending: Use the JSON Formatter to catch syntax errors early
  2. Use JSON5 for config files only: Don't send JSON5 to external APIs
  3. Strip comments: Remove comments before parsing strict JSON
  4. Automate formatting: Use tools (Prettier, ESLint) to enforce consistent JSON style
  5. Document with metadata: Instead of comments in JSON, use external documentation or a "_comment" key

Using Metadata Keys Instead of Comments

{
  "_comment": "User configuration - updated 2026-01-20",
  "name": "Alice",
  "age": 30,
  "active": true
}

Parser ignores "_comment" but humans can read it.

Tools for Working with JSON

Summary

  • JSON is strict: No trailing commas, no comments, double quotes only, quoted keys
  • JSONC/JSON5 add features: Comments, trailing commas, unquoted keys—but only work in specific tools
  • Common sources of non-standard JSON: Documentation examples, config files, JavaScript confusion
  • Fix errors: Use validators, remove comments, strip trailing commas
  • Best practice: Use strict JSON for APIs and data exchange; use JSON5 for human-edited config files

Validate your JSON with the JSON Formatter to catch trailing commas, comments, and syntax errors before they cause runtime issues.