What is JSON and Why Does Formatting Matter?
JSON (JavaScript Object Notation) is the de facto standard for data exchange on the web. Despite its simplicity, poorly formatted JSON is a common source of bugs and integration failures.
Proper JSON formatting matters for:
- Readability — well-formatted JSON is much easier to debug
- Collaboration — consistent formatting reduces merge conflicts
- Validation — catching errors before they reach production
- API contracts — ensuring data structure consistency
Basic JSON Structure
JSON supports six primitive types and two structural types:
{
"string": "Hello, World!",
"number": 42,
"float": 3.14159,
"boolean": true,
"null": null,
"array": [1, 2, 3],
"object": {
"nested": "value"
}
}
Common JSON Errors and How to Fix Them
1. Trailing Commas
JSON does not allow trailing commas (unlike JavaScript objects):
// ❌ Invalid
{
"name": "Alice",
"age": 30,
}
// ✅ Valid
{
"name": "Alice",
"age": 30
}
2. Single Quotes
JSON requires double quotes for strings:
// ❌ Invalid
{ 'name': 'Alice' }
// ✅ Valid
{ "name": "Alice" }
3. Unquoted Keys
All JSON keys must be quoted strings:
// ❌ Invalid
{ name: "Alice" }
// ✅ Valid
{ "name": "Alice" }
4. Comments
JSON does not support comments. Use a preprocessor like JSON5 if you need comments.
// ❌ Invalid — JSON has no comment syntax
{
// This is not valid
"name": "Alice" /* neither is this */
}
Formatting JSON in JavaScript
Using JSON.stringify
const data = { name: "Alice", age: 30, hobbies: ["reading", "coding"] };
// Compact (default)
JSON.stringify(data);
// '{"name":"Alice","age":30,"hobbies":["reading","coding"]}'
// Pretty-printed with 2-space indent
JSON.stringify(data, null, 2);
// {
// "name": "Alice",
// "age": 30,
// "hobbies": [
// "reading",
// "coding"
// ]
// }
// With key sorting (using replacer function)
const sorted = JSON.stringify(data, Object.keys(data).sort(), 2);
Parsing with Error Handling
Always wrap JSON.parse in try-catch:
function safeParseJSON(str) {
try {
return { data: JSON.parse(str), error: null };
} catch (error) {
return { data: null, error: error.message };
}
}
const { data, error } = safeParseJSON(userInput);
if (error) {
console.error('Invalid JSON:', error);
}
JSON Schema Validation
For API inputs, use JSON Schema to validate structure:
// Example schema
const userSchema = {
type: "object",
required: ["name", "email"],
properties: {
name: { type: "string", minLength: 1, maxLength: 100 },
email: { type: "string", format: "email" },
age: { type: "integer", minimum: 0, maximum: 150 }
},
additionalProperties: false
};
Libraries like Ajv or Zod (TypeScript) implement JSON Schema validation.
Quick Tools for JSON Work
Use our free browser-based tools:
- JSON Formatter — Beautify and minify JSON instantly
- JSON Validator — Validate with detailed error messages
Performance Considerations
For large JSON payloads:
// Stream large JSON instead of parsing all at once
// Use streaming parsers like 'stream-json' for Node.js
// For the browser, use Web Workers to avoid blocking the UI
const worker = new Worker('json-worker.js');
worker.postMessage({ json: largeJsonString });
worker.onmessage = (e) => {
const data = e.data;
// Use parsed data
};
Best Practices Summary
- Always validate JSON before using it in production
- Use 2-space indentation for readability in development
- Minify JSON for production APIs to reduce payload size
- Handle parse errors gracefully with try-catch
- Use a schema to validate structure for critical API endpoints
- Sort keys alphabetically in configuration files for easier diffs
JSON formatting is a small detail that has a big impact on developer experience. Use our JSON Formatter tool to quickly format any JSON you encounter.