Understanding JSON — Syntax Rules, Common Errors, and Best Practices for Developers
It's 11 PM, your API integration is due tomorrow morning, and you're staring at an "Unexpected token" error that makes no sense. The JSON looks fine. You've been over it three times. Then you spot it — a single trailing comma after the last property. Twenty minutes wasted on one character.
JSON Is Not JavaScript (and That Matters)
Here's what trips up almost every developer at some point: JSON looks like a JavaScript object literal, but it isn't one. They share a similar syntax, but JSON has stricter rules. Code that works perfectly as a JavaScript object can be completely invalid JSON.
JavaScript lets you use single quotes, unquoted keys, trailing commas, comments, and values like undefined. JSON allows none of these. This mismatch is the source of the majority of JSON errors developers encounter — they write JavaScript object syntax and expect it to work as JSON.
The JSON specification (RFC 8259) was deliberately made strict. The reasoning? If every JSON parser produces identical output from identical input regardless of programming language, data interchange becomes perfectly reliable. That strictness is a feature, not a limitation. But it means you need to know the rules.
The Complete JSON Syntax Rules
Let's go through every rule with examples. If you internalize these, you'll never write invalid JSON again.
Rule 1: Keys must be double-quoted strings.
✗ Wrong: {name: "John"}
✗ Wrong: {'name': "John"}
✓ Correct: {"name": "John"}
Rule 2: String values must use double quotes.
✗ Wrong: {"name": 'John'}
✓ Correct: {"name": "John"}
Rule 3: No trailing commas.
✗ Wrong: {"a": 1, "b": 2,}
✓ Correct: {"a": 1, "b": 2}
Rule 4: No comments.
✗ Wrong: {"name": "John" // user name}
✗ Wrong: {"name": "John" /* comment */}
✓ Correct: {"name": "John"}
Rule 5: Values can only be: string, number, boolean (true/false), null, object, or array.
✗ Wrong: {"value": undefined}
✗ Wrong: {"value": NaN}
✗ Wrong: {"value": Infinity}
✓ Correct: {"value": null}
Rule 6: Numbers cannot have leading zeros.
✗ Wrong: {"code": 007}
✓ Correct: {"code": 7}
The Top 5 JSON Errors Developers Make
In our experience building developer tools, these five errors account for roughly 90% of all JSON validation failures.
1. Trailing commas (40% of errors). This is the champion. JavaScript allows trailing commas and many developers rely on them for cleaner diffs in version control. JSON doesn't. Every time you add a new property at the end of an object, you add a comma after the previous one — and forget to check if the new property is actually the last one.
2. Single quotes (20% of errors). Python developers hit this constantly. Python's json.dumps() outputs proper double quotes, but when developers manually construct JSON strings, they often default to Python's preference for single quotes. JavaScript developers do the same with template literals.
3. Unquoted keys (15% of errors). In JavaScript, {name: "John"} is valid. In JSON, it isn't. This happens most often when developers paste JavaScript object literals from their code into API testing tools or configuration files.
4. Missing commas between properties (10% of errors). When manually editing JSON, it's easy to add a new line without adding the comma after the previous line. The error message usually says "Unexpected string" or "Expected comma" but points to the wrong line, making it confusing to debug.
5. Mismatched brackets or braces (5% of errors). In deeply nested JSON, losing track of opening and closing braces is easy. An object opened with { but closed with ] (or vice versa) produces an error that can be far from the actual problem location.
How to Debug JSON Errors Effectively
When a JSON validator says "Unexpected token at position 847," most people stare at the raw text trying to count characters. Here's a better approach.
Step 1: Use a validator with position reporting. Our JSON validator shows you exactly where the error is. Copy your JSON, paste it in, and click validate. The error message includes the character position and surrounding context.
Step 2: Beautify first, then validate. If beautification fails, you know the error is a fundamental syntax issue. If beautification succeeds but the data looks wrong, the issue might be in the data values rather than the syntax.
Step 3: Binary search for the error. If you have a huge JSON file and can't find the error, delete the second half and validate the first half. If it's valid, the error is in the second half. Keep halving until you isolate the problematic section.
Step 4: Check the line before the reported error. JSON parsers often report errors on the line after the actual mistake. If the error says "Unexpected token on line 15," the real problem is often a missing comma at the end of line 14.
JSON in the Real World: Who Uses It and How
🇮🇳 REST API Development — The Standard Data Format
Virtually every modern REST API sends and receives JSON. When you call the Razorpay API to process a payment, the request body is JSON. When Instagram's API returns your posts, the response is JSON. When your weather app shows the forecast, it parsed a JSON response from a weather API.
Takeaway: If you work with APIs, you work with JSON. Validation is essential for debugging request/response issues.
🇮🇳 Configuration Files — package.json and Beyond
Node.js projects use package.json for project configuration. VS Code uses settings.json for editor preferences. Docker uses docker-compose.json. AWS CloudFormation templates can be written in JSON. A syntax error in any of these files prevents the entire tool from starting.
Takeaway: Always validate config files after manual edits. A validator catches errors that would otherwise crash your application on startup.
🇬🇧 Data Storage and Transfer — MongoDB and NoSQL
MongoDB stores documents in BSON (Binary JSON), and queries are written in JSON-like syntax. Firebase Realtime Database stores all data as JSON. Many analytics platforms export data in JSON format for programmatic processing.
Takeaway: Invalid JSON in database operations can silently corrupt data or cause queries to fail. Validate before writing to any database.
JSON vs XML: Why JSON Won
Before JSON, XML was the dominant data interchange format. Here's why JSON replaced it for most use cases — and where XML still holds on.
JSON is more compact. The same data in JSON is typically 30-50% smaller than XML because JSON doesn't need closing tags, attributes, or namespaces. Less data means faster transmission.
JSON is easier to read. Compare {"name": "John", "age": 30} to <person><name>John</name><age>30</age></person>. The JSON version is immediately clear even to non-developers.
JSON maps directly to programming data structures. JSON objects map to dictionaries/hashmaps. JSON arrays map to lists/arrays. This makes parsing trivial in every language. XML requires parsing a document tree, which is more complex.
But XML still wins for: Document markup (HTML is XML-derived), data with complex schemas that need formal validation (XSD), data requiring mixed content (text with embedded elements), and legacy enterprise systems that predate JSON's popularity. SOAP APIs, RSS feeds, and SVG graphics all use XML and aren't switching anytime soon.
Best Practices for Working With JSON
- Always validate before sending. Validate JSON in your code before sending it to an API. Most languages have JSON libraries that throw errors on invalid syntax — catch them before they reach production.
- Use consistent formatting in source code. If you store JSON in your codebase, beautify it with 2-space indentation. This makes diffs readable in version control and errors easier to spot visually.
- Minify for transmission. When sending JSON over the network, minify it. The whitespace in beautified JSON serves no purpose for machines and adds 20-40% to payload size.
- Use meaningful key names.
{"fn": "John"}saves a few bytes but{"firstName": "John"}is self-documenting. Unless you're dealing with extreme bandwidth constraints, readable keys save debugging time. - Keep nesting shallow. Every level of nesting makes JSON harder to read and work with. If you find yourself at 5+ levels deep, consider flattening the structure or splitting into separate objects.
- Handle null explicitly. Use
nullfor missing values rather than omitting the key entirely. This makes it clear to consumers that the field exists but has no value, preventing "key not found" errors. - Don't store dates as strings without a format. Use ISO 8601 format (
"2025-01-24T10:30:00Z") consistently. Ambiguous date formats like "01/02/2025" cause parsing errors across different locales.
JSON5 and JSONC: When Standard JSON Isn't Enough
Standard JSON's strictness is great for data interchange but painful for configuration files. Developers want comments to explain settings and trailing commas for cleaner version control diffs. Two extensions address this.
JSON5 extends JSON with single-quoted strings, unquoted keys, trailing commas, comments (both // and /* */), multiline strings, hexadecimal numbers, and more. It's essentially "JavaScript object literal syntax that's also valid data format." Many tools support JSON5 for config files, including some parts of the Node.js ecosystem.
JSONC (JSON with Comments) is a simpler extension used by VS Code, TypeScript's tsconfig.json, and several Microsoft tools. It allows // and /* */ comments but otherwise follows standard JSON rules. It's the pragmatic middle ground — you get comments for documentation without changing the data model.
The key point: these extensions are for configuration files, not for API communication. When sending data between systems, always use standard JSON. When configuring tools locally, use whatever the tool supports — which increasingly includes JSON5 or JSONC.
Security Considerations With JSON
JSON itself is safe — it's just data. But how you handle JSON can create security vulnerabilities.
Never use eval() to parse JSON. In JavaScript, eval('(' + jsonString + ')') was historically used to parse JSON before JSON.parse() existed. This executes arbitrary code, meaning malicious JSON could run dangerous operations. Always use JSON.parse() which only parses data and never executes code.
Validate JSON structure, not just syntax. A syntactically valid JSON response from an API could contain unexpected fields, wrong data types, or malicious values. Schema validation (using JSON Schema) verifies that the structure matches what your code expects.
Watch for JSON injection. If you're constructing JSON by concatenating strings instead of using a proper serialization library, user input could inject additional fields. A username of "John", "admin": true, "x": " could modify the structure. Always use language-level JSON serializers.
Limit payload size. Accepting unlimited JSON payloads from clients opens the door to denial-of-service attacks. Set reasonable limits on request body size in your API server configuration.
JSON Validation Across Languages
Understanding JSON Validation Globally
When You Should Validate JSON
Not every situation needs a dedicated validation step. Here's when it matters most.
Always validate: Before sending API requests (especially when constructing JSON manually), after manually editing configuration files, when receiving JSON from untrusted external sources, before writing JSON to databases, and when migrating data between systems.
Validation is built-in: When using JSON.parse() in JavaScript, json.loads() in Python, json_decode() in PHP, or equivalent functions in any language — these validate syntax automatically and throw errors on invalid input. You don't need a separate validation step if you're already parsing with standard library functions.
Consider schema validation for: API contracts where the structure matters as much as the syntax, data imports from external partners where you can't control the format, and any system where wrong data types (a string where a number should be) could cause downstream failures.
Validate Your JSON Now
Need to check, format, or minify JSON? Use our validator with instant syntax checking, beautification, minification, and detailed error reporting.
Validate JSON Now →Recommended Hosting
Hostinger
If you are building a website for your tools, blog, or store, reliable hosting matters for speed and uptime. Hostinger is a popular option used worldwide.
Visit Hostinger →Disclosure: This is a sponsored link.
