JSON Syntax Guide: Common Errors and How to Fix Them
A complete guide to JSON syntax rules, the most frequent mistakes developers make, and practical strategies for identifying and resolving parse errors.
The JSON Specification in Brief
JSON (JavaScript Object Notation) was formalized by Douglas Crockford in the early 2000s and standardized as ECMA-404 and RFC 8259. Despite its name, JSON is language-independent and used across virtually every programming ecosystem. Its success comes from a remarkably small set of rules, but those rules are strict. Understanding them is essential for every developer who works with APIs, configuration files, or data interchange.
For the complete specification reference with exact RFC 8259 / ECMA-404 citations and a live spec checker, see our JSON Specification Compliance Guide.
The Six Fundamental Rules
JSON has exactly six data types: strings, numbers, booleans, null, arrays, and objects. Every valid JSON document is built from these primitives, and every parse error traces back to violating one of the following rules.
Rule 1: Strings Must Use Double Quotes (RFC 8259 §7)
JSON strings must be enclosed in double quotes ("). Single quotes, backticks, and unquoted strings are all invalid. This is the single most common source of errors for developers coming from JavaScript or Python, where single quotes are interchangeable with double quotes.
// INVALID - single quotes
{ 'name': 'Alice' }
// VALID - double quotes
{ "name": "Alice" }Rule 2: Object Keys Must Be Strings (RFC 8259 §4)
Every key in a JSON object must be a double-quoted string. Unquoted keys are valid in JavaScript objects but not in JSON. This distinction trips up many developers who write JSON by hand.
// INVALID - unquoted keys
{ name: "Alice", age: 30 }
// VALID - quoted keys
{ "name": "Alice", "age": 30 }Rule 3: No Trailing Commas (RFC 8259 §4-5)
JSON does not allow a comma after the last element in an array or the last key-value pair in an object. JavaScript has allowed trailing commas since ES5, so this is another common error when writing JSON by hand or converting from a JavaScript object literal.
// INVALID - trailing comma after "cron"
{
"tools": ["epoch", "json", "cron",]
}
// VALID - no trailing comma
{
"tools": ["epoch", "json", "cron"]
}Rule 4: No Comments (ECMA-404 / RFC 8259)
JSON does not support comments of any kind. No // line comments, no /* */ block comments. This is a deliberate design decision: JSON is a data format, not a programming language. If you need comments in configuration files, consider using JSONC (JSON with Comments) or YAML, which supports comments natively.
// INVALID - comments not allowed
{
// This is the user's name
"name": "Alice", /* inline comment */
"role": "admin"
}
// VALID - no comments
{
"name": "Alice",
"role": "admin"
}Rule 5: Numbers Follow Strict Rules
JSON numbers cannot have leading zeros (except for 0 itself or 0.5-style decimals), cannot use hexadecimal notation, and must not include NaN, Infinity, or -Infinity. These are all valid in JavaScript but invalid in JSON.
// INVALID
{ "port": 08080 } // leading zero
{ "mask": 0xFF } // hex notation
{ "ratio": NaN } // NaN not allowed
{ "limit": Infinity } // Infinity not allowed
// VALID
{ "port": 8080 }
{ "mask": 255 }
{ "ratio": 0 }
{ "limit": 999999999 }Rule 6: Strings Have Specific Escape Sequences
Within a JSON string, only certain escape sequences are valid: \\", \\\\, \\/, \\b, \\f, \\n, \\r, \\t, and Unicode escapes like \\u0041. Using invalid escape sequences such as \\x41 (hex escape) or \\' (single quote escape) will cause a parse error.
Common Error Patterns and Fixes
After reviewing thousands of JSON parsing errors across developer forums and issue trackers, a clear set of recurring patterns emerges. Here are the most frequent errors with practical before-and-after fixes.
Unexpected Token at Position 0
This error typically means the input is not JSON at all. Common causes include accidentally pasting a JavaScript object literal, an XML document, or a string that was double-encoded (JSON inside a JSON string).
// Double-encoded JSON (string wrapping JSON)
"{\"name\": \"Alice\"}"
// Fix: parse once to get the inner string, then parse again
const inner = JSON.parse(outerString);
const data = JSON.parse(inner);Unexpected End of JSON Input
This error means the parser reached the end of the string before finding a complete JSON value. The most common causes are truncated responses from APIs (network timeout) and missing closing brackets or braces.
// Missing closing brace
{
"name": "Alice",
"age": 30
// Fix: add the closing brace
{
"name": "Alice",
"age": 30
}Mixed Delimiters in Nested Structures
When manually constructing JSON with deeply nested objects and arrays, it is easy to confuse {} (objects) with [] (arrays). Parsers will report an unexpected token at the point where the wrong delimiter appears.
How Different Parsers Handle Errors
Not all JSON parsers produce the same error messages. Understanding the differences can help you debug faster depending on your environment.
- V8 (Node.js, Chrome): Reports “Unexpected token X at position N” with a character offset. Useful for pinpointing the exact location.
- SpiderMonkey (Firefox): Reports line and column numbers directly, which is more useful for multi-line JSON.
- Python json module: Provides both line/column and a snippet of context around the error. Generally the most developer-friendly error messages.
- jq: Reports errors with a character offset and an excerpt of the surrounding text. Particularly useful for debugging JSON streams.
Auto-Fix Strategies
Some JSON errors can be automatically repaired. Our JSON Formatter includes an Auto Fix feature that applies these strategies in order:
- Strip comments: Remove
//and/* */comments while preserving strings that contain comment-like patterns. - Replace single quotes: Convert single-quoted strings and keys to double-quoted equivalents, handling escaped quotes inside strings.
- Quote unquoted keys: Detect bare identifiers used as object keys and wrap them in double quotes.
- Remove trailing commas: Delete commas that appear immediately before
}or].
These repairs are applied conservatively. If the result still fails to parse, the tool reports the remaining error so you can fix it manually.
Validation in Your Workflow
Rather than discovering JSON errors at runtime, integrate validation into your development workflow:
- Editor integration: Most code editors (VS Code, IntelliJ, Vim) validate JSON files on save and highlight errors inline.
- Pre-commit hooks: Use tools like
jsonlintorjqin git pre-commit hooks to catch malformed JSON before it enters the repository. - CI/CD pipelines: Validate JSON configuration files as part of your build process. A single trailing comma in a config file can bring down a deployment.
- API response validation: Use JSON Schema to validate the structure and types of API responses, not just whether the JSON parses.
JSON in Infrastructure: Network Configuration
JSON is the lingua franca of infrastructure-as-code. Tools like Terraform, AWS CloudFormation, and Kubernetes all use JSON (or JSON-compatible formats) for defining network infrastructure. A common example is specifying VPC subnets and CIDR blocks in Terraform:
{
"resource": {
"aws_vpc": {
"main": {
"cidr_block": "10.0.0.0/16",
"enable_dns_support": true
}
},
"aws_subnet": {
"public": {
"vpc_id": "${aws_vpc.main.id}",
"cidr_block": "10.0.1.0/24",
"availability_zone": "us-east-1a"
}
}
}
}A misplaced comma or missing quote in these configuration files can prevent entire deployments. Use our JSON Formatter to validate infrastructure configs before applying them, and our Subnet Calculator to verify that the CIDR blocks in your configs are correctly sized and do not overlap.
JSON in Authentication: JWT Payloads
One of the most common places developers encounter JSON in the wild is inside JSON Web Tokens (JWTs). A JWT is composed of three Base64URL-encoded segments separated by dots, and both the header and payload segments are JSON objects. The header typically contains the signing algorithm, while the payload carries claims like user identity and token expiration. Because these are standard JSON, all the syntax rules above apply -- a malformed payload will cause decoding failures. If you are working with JWTs, our What is a JWT? guide explains the structure in detail, and the JWT Decoder lets you paste a token to inspect its JSON header and payload.
Try It Yourself
Paste any JSON into our JSON Formatter & Validator to instantly see validation results, error locations, and auto-fix suggestions. The tool processes everything in your browser, so your data remains private. You can also explore the JSONPath Tutorial to learn how to query and extract data from complex JSON documents.
Further Reading
- ECMA-404 — The JSON Data Interchange Syntax
The ECMA International standard defining JSON syntax.
- RFC 8259 — The JSON Data Interchange Format
The IETF standard for JSON, specifying encoding and interoperability rules.
- JSON.org
The original JSON specification with railroad diagrams for the grammar.
- MDN JSON reference
JavaScript JSON parsing and serialization documentation.
Related Articles
- JSON vs YAML: Complete Comparison with Examples
- JSONPath Tutorial: Query and Extract JSON Data
- Introduction to JSON Schema: Validate Your Data
- Epoch Converter - Work with Unix Timestamps in JSON
- What is a JWT? Understanding JSON Web Tokens
- Subnet Calculator -- Verify CIDR blocks in JSON infrastructure configs