JSON Standards

JSON Trailing Commas & RFC 8259: Why They Break Your Code (And How to Fix It)

📅 December 17, 2025 âąī¸ 11 min read đŸ‘ī¸ 15 views đŸˇī¸ JSON Standards

If you've ever seen an error like Expected comma or closing brace or Unexpected token } while working with JSON, there's a good chance you've hit one of the most common JSON pitfalls: trailing commas. Let's clear this up once and for all trailing commas are NOT allowed in JSON according to RFC 8259, the official JSON specification.

This article will explain exactly why trailing commas break JSON, what RFC 8259 says about them, and how to quickly detect and fix this issue in your projects.

What Is RFC 8259?

RFC 8259 (published in December 2017) is the official specification for JSON (JavaScript Object Notation). RFC stands for "Request for Comments," which is how internet standards are documented. RFC 8259 supersedes the earlier RFC 7159 and aligns with ECMA-404, the JSON data interchange standard.

In simple terms, RFC 8259 is the "rule book" that defines:

  • What constitutes valid JSON syntax
  • How JSON parsers should interpret data
  • The exact grammar rules for strings, numbers, objects, arrays, booleans, and null values

Every major programming language, browser, and API framework follows RFC 8259 when parsing JSON. This means if your JSON doesn't comply with RFC 8259, it will fail in Python, JavaScript, Java, Go, Ruby, PHP, and virtually every other environment.

Why RFC 8259 Compliance Matters

JSON is the universal language of data exchange on the web. APIs, configuration files, databases, and countless applications rely on JSON. When your JSON violates RFC 8259:

  • API calls fail Servers reject malformed JSON payloads
  • Applications crash Config files with syntax errors break your app on startup
  • Data gets lost Parsers may silently fail or corrupt data
  • Interoperability breaks What works in one tool may fail in another

Are Trailing Commas Allowed in JSON?

❌ No. Trailing commas are NOT allowed in JSON according to RFC 8259.

This is the definitive answer. Unlike JavaScript (where trailing commas are perfectly valid), JSON has strict syntax rules that prohibit a comma after the last element in an array or object.

❌ Invalid JSON (with trailing comma)

{
  "name": "John Doe",
  "age": 30,
  "city": "New York",  ← Trailing comma here!
}
{
  "colors": [
    "red",
    "green",
    "blue",  ← Trailing comma in array!
  ]
}

✅ Valid JSON (without trailing comma)

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}
{
  "colors": [
    "red",
    "green",
    "blue"
  ]
}

Notice the only difference is the removal of the comma after the last element. That single character is the difference between valid and invalid JSON.

Why Trailing Commas Break JSON

To understand why trailing commas are invalid, we need to look at the JSON grammar defined in RFC 8259.

The JSON Grammar

According to RFC 8259, a JSON object is defined as:

object = begin-object [ member *( value-separator member ) ] end-object

Where:
- begin-object = { (left curly brace)
- end-object = } (right curly brace)  
- value-separator = , (comma)
- member = string : value

This grammar specifies that commas separate members they appear between elements, not after the last one. The pattern is:

{ member, member, member }
      ↑        ↑
   separators (between items only)

A trailing comma would create this invalid pattern:

{ member, member, member, }
      ↑        ↑        ↑
                     invalid!

The parser expects another member after the comma, but instead finds a closing brace. This is a grammar violation.

JSON vs JavaScript: A Crucial Difference

One of the most common sources of confusion is that JavaScript allows trailing commas, but JSON does not. Many developers write JSON like they write JavaScript objects, leading to syntax errors.

Feature JSON JavaScript
Trailing commas ❌ Not allowed ✅ Allowed (ES5+)
Comments ❌ Not allowed ✅ Allowed
Unquoted keys ❌ Not allowed ✅ Allowed
Single quotes ❌ Must use double quotes ✅ Both allowed
Specification RFC 8259 / ECMA-404 ECMAScript
Primary use Data interchange Programming language

Why Some Editors Allow Trailing Commas

You might wonder: "If trailing commas are invalid, why does my editor accept them?"

Some editors and IDEs are lenient by default. They may:

  • Use a JavaScript parser instead of a strict JSON parser
  • Support JSON5 or JSONC (JSON with Comments) which allow trailing commas
  • Prioritize developer experience over strict compliance

However, just because your editor accepts it doesn't mean your API, server, or application will. Always validate against RFC 8259 before using JSON in production.

Common JSON Trailing Comma Errors

Here are the most common error messages you'll encounter when trailing commas are present:

1. "Expected comma or closing brace"

SyntaxError: Expected comma or closing brace in JSON at position 45

Why it happens: This error is slightly misleading. The parser found an unexpected token (often because of a trailing comma before a closing brace) and is reporting what it expected to find instead.

2. "Unexpected token }"

SyntaxError: Unexpected token } in JSON at position 52

Why it happens: After reading a comma, the parser expects another value (key-value pair or array element). Instead, it found a closing brace } or bracket ], which is unexpected.

3. "Unexpected end of JSON input"

SyntaxError: Unexpected end of JSON input

Why it happens: This can occur when the parser reaches the end of the input while still expecting more data (perhaps because a trailing comma suggested more data was coming).

4. "Parse error: trailing comma"

JSON Parse error: Trailing comma in object

Why it happens: Some parsers explicitly detect and report trailing commas with this clear message. This is the most helpful error as it tells you exactly what's wrong.

5. "Bad escaped character in JSON"

Why it happens: While not directly caused by trailing commas, this error sometimes appears in conjunction with other JSON syntax issues when parsers get confused by malformed input.

How to Detect and Fix Trailing Commas

There are two main approaches to finding and fixing trailing commas in your JSON:

Method 1: Manual Inspection

For small JSON files, you can manually scan for trailing commas:

  1. Look for commas immediately before } (closing brace)
  2. Look for commas immediately before ] (closing bracket)
  3. Check the last element in every object and array

Limitations: This is tedious, error-prone, and impractical for large files.

Method 2: Use an Online JSON Validator (Recommended)

Instead of manually scanning files, use a dedicated JSON Validator & Formatter to instantly detect trailing commas and other RFC 8259 violations.

Our JSON validation tool:

  • Detects RFC 8259 violations Including trailing commas, invalid quotes, and syntax errors
  • Highlights the exact error location Jump directly to the problematic line
  • Works online without signup Free, instant, no account required
  • Handles large JSON files Process megabytes of JSON data efficiently
  • 100% client-side Your data never leaves your browser

Simply paste your JSON, click validate, and get instant feedback on any syntax issues.

Real-World Scenarios Where Trailing Commas Cause Problems

1. API Request Failures

// This will fail when sent to an API
const payload = `{
  "username": "johndoe",
  "email": "john@example.com",
}`;

fetch('/api/users', {
  method: 'POST',
  body: payload,  // Server returns 400 Bad Request
  headers: { 'Content-Type': 'application/json' }
});

Many developers craft JSON manually (especially in testing tools like Postman) and accidentally include trailing commas. The API server will reject the request with a 400 Bad Request error.

2. Configuration File Crashes

// package.json with trailing comma
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node index.js",
    "test": "jest",  ← Trailing comma
  }
}

npm and yarn will fail to parse this package.json, preventing your project from installing dependencies or running scripts.

3. Environment Config Failures

// .eslintrc.json with trailing comma
{
  "env": {
    "browser": true,
    "es2021": true,
  }  ← ESLint will crash on startup
}

4. Database Document Rejections

Document databases like MongoDB, CouchDB, and Firebase Firestore all use JSON. Inserting documents with trailing commas will result in insertion failures.

How to Prevent Trailing Comma Issues

1. Configure Your Linter

Use ESLint with the comma-dangle rule to catch trailing commas in JavaScript code that generates JSON:

{
  "rules": {
    "comma-dangle": ["error", "never"]
  }
}

2. Use Prettier for Formatting

Configure Prettier to automatically remove trailing commas:

{
  "trailingComma": "none"
}

3. Validate Before Committing

Add a pre-commit hook to validate all JSON files:

# In package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "node -e 'JSON.parse(require("fs").readFileSync("config.json"))'"
    }
  }
}

4. Use JSON Schema Validation

Implement schema validation in your CI/CD pipeline to catch JSON errors before deployment.

What About JSON5 and JSONC?

If you genuinely need trailing commas for developer convenience, consider these JSON variants:

JSON5

JSON5 is an extension of JSON that adds JavaScript-like features:

  • ✅ Trailing commas allowed
  • ✅ Single and double quotes
  • ✅ Comments (single and multi-line)
  • ✅ Unquoted keys
// JSON5 example (trailing comma allowed)
{
  name: 'John Doe',
  age: 30,
  city: "New York",  // This is valid JSON5!
}

Note: JSON5 requires a special parser. Standard JSON parsers will reject JSON5 files.

JSONC (JSON with Comments)

JSONC is used by VS Code for its configuration files. It allows comments but technically also permits trailing commas in many implementations.

// JSONC example (VS Code settings.json)
{
  // Editor settings
  "editor.fontSize": 14,
  "editor.tabSize": 2,  // Trailing comma often tolerated
}

Important: While these formats are convenient for config files, always use strict RFC 8259 JSON for APIs and data interchange.

Frequently Asked Questions

Are trailing commas allowed in JSON RFC 8259?

No. RFC 8259 explicitly prohibits trailing commas. The JSON grammar specifies that commas must separate elements, not follow the last element. A trailing comma before a closing brace } or bracket ] is a syntax error.

Why does my editor allow trailing commas in JSON?

Many editors use lenient parsers or support JSON5/JSONC formats that allow trailing commas. However, this doesn't mean the JSON is valid according to RFC 8259. Always validate with a strict JSON parser before using in production.

Can APIs accept trailing commas in JSON?

No. Standard API servers use RFC 8259-compliant JSON parsers that will reject requests with trailing commas. The server will typically return a 400 Bad Request error with a message about invalid JSON syntax.

How do I quickly validate JSON for trailing commas?

Use an online JSON Validator to instantly check your JSON for RFC 8259 compliance. Our tool highlights the exact location of syntax errors including trailing commas.

Why do some JSON files work with trailing commas?

Some tools (like VS Code for its settings files) use JSONC or JSON5 parsers that are more lenient. However, these files won't work with standard JSON parsers used by APIs, databases, and most programming languages.

Is there a JSON format that allows trailing commas?

Yes, JSON5 and JSONC both allow trailing commas. However, these formats require special parsers and should only be used for configuration files, not data interchange.

Conclusion

Trailing commas are one of the most common causes of JSON parsing errors. Despite their convenience in JavaScript, they are strictly prohibited in JSON according to RFC 8259.

Key takeaways:

  • ❌ Trailing commas are NOT allowed in RFC 8259-compliant JSON
  • âš ī¸ Your editor may be lenient but production systems are not
  • 🔧 Always validate JSON before using it in APIs or configurations
  • 📋 Use a JSON validator to instantly detect trailing commas
  • ✨ Consider JSON5 for config files if you need trailing comma support

The next time you see Unexpected token } or Expected comma or closing brace, check for trailing commas first it's almost always the culprit.

Validate Your JSON Now →


Related Tools

đŸˇī¸ Tags:
json rfc 8259 trailing comma json syntax error json parse error json validation json standard json specification api errors json formatting