JSON is everywhere. It's the default data format for web APIs, configuration files, databases, log systems, and inter-service communication. Most developers work with JSON daily — and most developers have spent time staring at a cryptic "Unexpected token" error wondering which line broke.
JSON's simplicity is both its strength and its weakness. The format is easy to understand but unforgiving of mistakes. A single misplaced comma or missing quote renders an entire document invalid. This guide covers the common pitfalls, the tools that help, and the formatting practices that prevent errors in the first place.
Why JSON Validation Matters
Invalid JSON doesn't just fail silently — it causes cascading problems.
An API response with a malformed JSON body will crash the client parsing it. A configuration file with a trailing comma will prevent your application from starting. A data pipeline that encounters invalid JSON in one record may halt processing of the entire batch.
The challenge is that JSON errors are often invisible to the human eye. A missing closing brace 200 lines into a file, an unescaped control character in a string value, a number with a leading zero — these are easy to miss in a visual scan but will cause immediate parsing failures.
Validation catches these problems before they reach production.
Common JSON Errors (and How to Fix Them)
After years of working with JSON, certain errors appear far more frequently than others. Here are the most common, with examples and fixes.
Trailing Commas
The single most common JSON error. JavaScript allows trailing commas in arrays and objects. JSON does not.
// Invalid JSON
{
"name": "Alice",
"age": 30,
}
// Valid JSON
{
"name": "Alice",
"age": 30
}
This error is especially common when developers copy data structures from JavaScript code into JSON files. Every modern linter can catch this, but it still appears constantly in hand-edited JSON.
Single Quotes Instead of Double Quotes
JSON requires double quotes for strings. Single quotes are not valid.
// Invalid JSON
{
'name': 'Alice'
}
// Valid JSON
{
"name": "Alice"
}
Python developers are particularly prone to this error because Python's json.dumps() uses double quotes, but Python's default string representation uses single quotes. Copying from a Python REPL into a JSON file often introduces this problem.
Unquoted Keys
In JavaScript, object keys don't need quotes (unless they contain special characters). In JSON, every key must be a double-quoted string.
// Invalid JSON
{
name: "Alice"
}
// Valid JSON
{
"name": "Alice"
}
Comments
JSON does not support comments. No //, no /* */, no #. This is one of JSON's most criticized limitations.
// Invalid JSON
{
"port": 3000, // default port
"debug": true
}
// Valid JSON
{
"port": 3000,
"debug": true
}
If you need comments in configuration files, consider JSONC (JSON with Comments, supported by VS Code's settings files), JSON5, YAML, or TOML. But if the downstream consumer expects standard JSON, comments must be removed.
Unescaped Special Characters
String values must escape certain characters: double quotes, backslashes, and control characters.
// Invalid JSON
{
"path": "C:\Users\data",
"quote": "She said "hello""
}
// Valid JSON
{
"path": "C:\\Users\\data",
"quote": "She said \"hello\""
}
Windows file paths are a frequent source of this error due to backslashes. Tab characters, newlines, and other control characters within strings must also be escaped (\t, \n, etc.).
Leading Zeros in Numbers
JSON numbers cannot have leading zeros (except for 0 itself and 0.xxx decimal numbers).
// Invalid JSON
{
"zipCode": 01234
}
// Valid JSON
{
"zipCode": "01234"
}
Zip codes, phone numbers, and other numeric-looking values that can start with zero should be stored as strings.
Mismatched Brackets and Braces
In deeply nested JSON, it's easy to lose track of opening and closing brackets.
// Invalid JSON
{
"users": [
{"name": "Alice"},
{"name": "Bob"}
}
// Valid JSON
{
"users": [
{"name": "Alice"},
{"name": "Bob"}
]
}
This error becomes common in JSON files longer than a few dozen lines. Proper indentation and a good editor with bracket matching are the best defenses.
Using undefined, NaN, or Infinity
These are valid JavaScript values but not valid JSON.
// Invalid JSON
{
"value": undefined,
"ratio": NaN,
"max": Infinity
}
// Valid JSON
{
"value": null,
"ratio": null,
"max": null
}
Use null to represent missing values. For special numeric values, you'll need application-level conventions (e.g., storing "NaN" as a string or using a sentinel value).
JSON Formatting Conventions
Well-formatted JSON prevents errors and makes debugging easier. Here are the conventions that matter.
Indentation: 2 Spaces vs 4 Spaces vs Tabs
The three common indentation styles each have their adherents:
- 2 spaces — the most common convention, used by most JavaScript/TypeScript projects, npm, and major tech companies. Keeps deeply nested structures readable without excessive horizontal scrolling.
- 4 spaces — common in Python ecosystems and some enterprise codebases. More visually distinct nesting but uses more horizontal space.
- Tabs — technically valid but rare in JSON. Most JSON formatters default to spaces.
The right answer for your project is whichever convention your team already uses. Consistency matters more than the specific choice. If starting fresh, 2 spaces is the safest default.
Key Ordering
JSON objects are technically unordered — the spec doesn't guarantee key order. But human-readable JSON benefits from consistent key ordering.
Common approaches:
- Alphabetical — predictable and easy to scan. Good for configuration files and schemas.
- Logical grouping — related keys together (e.g., all database settings, then all cache settings). Better for complex config files.
- Importance-first — the most important or commonly modified keys at the top. Useful for frequently hand-edited files.
Many teams enforce key ordering through linters or pre-commit hooks. json-sort-keys in ESLint or sort-keys-fix can automate this.
Line Length
JSON doesn't have a line length limit, but extremely long lines make diff reviews difficult. When a single JSON value is very long (like a base64-encoded string), consider whether it belongs in a separate file or should be split across lines using array notation.
For JSON that will be diff-reviewed in pull requests, keeping individual values under 120 characters per line is a practical guideline.
Validation Strategies
Schema Validation with JSON Schema
Beyond syntax validation, JSON Schema lets you define the structure, types, and constraints that a JSON document must satisfy.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 0 },
"email": { "type": "string", "format": "email" }
},
"required": ["name", "email"]
}
JSON Schema validation catches not just syntax errors but semantic errors: a missing required field, a string where a number is expected, a value outside an allowed range. For APIs and configuration files, schema validation is significantly more useful than syntax validation alone.
API Response Validation
When consuming external APIs, never trust that the response matches the documented schema. Network errors, API version changes, and provider bugs can all produce unexpected JSON.
Best practices:
- Validate the response is valid JSON before parsing
- Validate the parsed structure against an expected schema
- Handle validation failures gracefully (log, retry, or degrade)
TypeScript's type system provides compile-time structure checking, but runtime validation libraries like Zod, Yup, or Ajv catch issues that TypeScript cannot — because TypeScript types are erased at runtime.
Configuration File Validation
Configuration files are a common source of production incidents. A typo in a JSON config can bring down a service. Defense strategies include:
- Schema validation in CI — validate all JSON config files against their schemas as part of the build pipeline
- Environment-specific validation — verify that production configs include all required fields, even if development configs allow defaults
- Pre-commit hooks — catch invalid JSON before it's committed
Working with JSON: Practical Tools
Formatting and Beautifying
Minified JSON — a single line with no whitespace — is efficient for transmission but impossible for humans to read. Formatting (or "beautifying") adds indentation and line breaks.
FileMuncher's JSON Formatter validates and formats JSON in your browser. Paste minified or messy JSON, and get properly indented output instantly. This is especially useful when inspecting API responses, debugging webhook payloads, or cleaning up machine-generated configuration files. Because it runs locally, you can safely format JSON containing API keys, tokens, or other sensitive data without sending it to a server.
Comparing JSON Documents
When debugging API changes or comparing configuration versions, you need to see exactly what differs between two JSON documents. Standard text diff tools work but produce noisy output because key order, whitespace, and formatting differences create false positives.
Semantic JSON diff tools normalize the structure before comparing, showing only meaningful differences. FileMuncher's Text Diff tool can compare two JSON documents side-by-side, making it easy to spot the actual changes amid formatting noise.
Encoding and Transforming
JSON data often needs to be encoded for transmission or storage — Base64 encoding for embedding in other documents, URL encoding for query parameters, or hex encoding for binary data represented as JSON strings.
FileMuncher's Encoder/Decoder handles these transformations locally. This is particularly relevant when debugging encoded JSON payloads — decode a Base64 string to see the JSON inside, then format it for readability.
JSON in the Real World
Package.json and Lock Files
JavaScript's package.json is probably the most widely hand-edited JSON file in existence. Common issues:
- Trailing commas after adding a new dependency
- Version strings that don't follow semver (
"1.2"instead of"1.2.0") - Duplicate keys (JSON allows them syntactically, but behavior is undefined — parsers typically use the last value)
Lock files (package-lock.json, pnpm-lock.yaml) should never be hand-edited. If a lock file has a JSON syntax error, regenerate it rather than trying to fix it manually.
API Design and JSON
When designing JSON APIs, formatting choices affect both usability and debugging:
- Use consistent naming conventions.
camelCaseis standard in JavaScript ecosystems;snake_caseis common in Python/Ruby APIs. Pick one and enforce it. - Use null, not absent keys, for missing values. A key with a
nullvalue communicates "this field exists but has no value." An absent key is ambiguous — is the field unsupported, or was there a serialization error? - Avoid deeply nested structures. Each level of nesting adds cognitive load and parsing complexity. If your JSON regularly exceeds 4-5 levels of nesting, consider flattening the structure.
- Include metadata at the top level. Pagination info, request IDs, and timestamps at the root level make API responses easier to handle generically.
JSON and Security
JSON parsing has security implications beyond validation:
- JSON injection — when user input is interpolated into JSON strings without proper escaping, attackers can modify the JSON structure. Always use
JSON.stringify()or equivalent safe serialization. - Prototype pollution — in JavaScript, parsing JSON with certain key names (
__proto__,constructor) can modify object prototypes. UseObject.create(null)or dedicated libraries that sanitize parsed output. - Denial of service — deeply nested JSON or extremely large JSON documents can exhaust parser memory. Set maximum depth and size limits on incoming JSON.
JSON Alternatives: When to Use Something Else
JSON isn't always the best choice:
- YAML — better for configuration files (supports comments, multi-line strings, anchors). Worse for data interchange (whitespace-sensitive, complex spec, security concerns with arbitrary code execution in some parsers).
- TOML — excellent for simple, flat configuration. Cleaner than JSON for config but limited for complex nested data.
- Protocol Buffers / MessagePack — binary formats that are smaller and faster to parse than JSON. Better for high-throughput inter-service communication. Worse for human readability and debugging.
- CSV — better for tabular data that will be analyzed in spreadsheets. Worse for nested or typed data.
For most web applications, JSON remains the right default. Its universal support across languages, tools, and platforms is an advantage that alternatives can't match.
Frequently Asked Questions
Why doesn't JSON support comments?
Douglas Crockford, JSON's creator, intentionally excluded comments. His reasoning: comments in configuration files were being used for parsing directives (like in XML), which he wanted to prevent. The community has largely worked around this with JSONC and JSON5 for configuration files, while keeping standard JSON comment-free for data interchange.
Is there a maximum size for a JSON file?
The JSON spec doesn't define a maximum size. Practical limits depend on the parser and available memory. Most JavaScript engines can parse JSON files up to several hundred megabytes. For very large datasets, consider streaming parsers (like JSONStream in Node.js) that process the data incrementally without loading the entire document into memory.
How do I validate JSON without installing anything?
Browser-based tools like FileMuncher's JSON Formatter validate JSON instantly in your browser. Paste your JSON, and the tool will identify syntax errors with line numbers and descriptions. No installation, no signup, and your data stays on your device.
Should I pretty-print JSON in API responses?
In production, no — minified JSON saves bandwidth. In development and staging environments, pretty-printed responses are much easier to debug. Most API frameworks support a query parameter (like ?pretty=true) to toggle formatting.
What's the difference between JSON and JSON5?
JSON5 extends JSON with features developers frequently want: comments, trailing commas, single-quoted strings, unquoted keys, multi-line strings, and additional number formats (hex, Infinity, NaN). JSON5 is useful for configuration files but is not a replacement for standard JSON in APIs, as most parsers and tools expect standard JSON.
Working with JSON? Format and validate your JSON instantly with FileMuncher — runs in your browser, no data sent to any server.