JSON (JavaScript Object Notation) is the standard format for data exchange on the web. Every modern API speaks JSON, configuration files use it, and databases store it. Proper formatting and validation are essential skills for anyone working with web technologies. The JSON Formatter makes validation and beautification instant, helping you debug and understand JSON data quickly.
What is JSON?
JSON is a lightweight data format that is easy for humans to read and machines to parse. It uses key-value pairs and arrays to represent structured data in a text format that works across all programming languages.
Originally derived from JavaScript object syntax, JSON has become the universal standard for web APIs, configuration files, data storage, and inter-system communication. Despite its JavaScript roots, JSON is language-independent and supported by virtually every modern programming environment.
The format was formalized in 2006 (ECMA-404) and has largely replaced XML for most data exchange purposes due to its simplicity and smaller size.
Why JSON Matters
JSON has become ubiquitous for several important reasons:
- API Communication: REST APIs universally use JSON for requests and responses
- Configuration: Package managers, build tools, and applications use JSON for settings
- Data Storage: NoSQL databases like MongoDB store JSON documents natively
- Cross-Platform: JSON works identically across all languages and systems
- Human Readable: Unlike binary formats, developers can read and debug JSON directly
JSON Syntax Rules
JSON follows strict syntax rules that must be followed exactly for valid data:
- Key-value pairs: Data is organized as key-value pairs separated by colons
- Quoted keys: All keys must be strings in double quotes (never single quotes)
- Value types: Values can be strings, numbers, booleans (true/false), arrays, objects, or null
- Objects: Use curly braces { } for objects (unordered collections of key-value pairs)
- Arrays: Use square brackets [ ] for arrays (ordered lists of values)
- Commas: Items are separated by commas (no trailing commas allowed)
- No comments: Standard JSON does not support any form of comments
Common Use Cases
API Development and Testing
Developers constantly work with JSON when building and consuming APIs. Formatting minified API responses makes them readable for debugging, while validating request bodies catches errors before sending.
Configuration Management
Files like package.json (Node.js), composer.json (PHP), and app configuration files require valid JSON. A single syntax error can prevent applications from starting.
Data Migration
Moving data between systems often involves JSON exports and imports. Validating JSON before import prevents failed migrations and data corruption.
Documentation and Examples
API documentation includes JSON examples that must be valid. Formatting ensures examples are readable and correct.
Format and Validate JSON Instantly
The JSON Formatter provides comprehensive JSON processing:
- Beautify: Format minified JSON into readable, indented structure
- Validate: Check JSON syntax and report any errors
- Error detection: Identify exactly where syntax errors occur with line numbers
- Minify: Compress JSON by removing whitespace for production use
- Tree view: Visualize JSON structure hierarchically
No registration required, and your data stays private as all processing happens in your browser.
Valid JSON Example
Here is an example of properly formatted JSON with various data types:
{
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"active": true,
"balance": 1250.50,
"roles": ["admin", "user", "moderator"],
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001",
"country": "USA"
},
"preferences": null,
"loginHistory": [
{"date": "2024-01-15", "ip": "192.168.1.1"},
{"date": "2024-01-10", "ip": "192.168.1.2"}
]
}
Common JSON Errors
Trailing Commas
JSON does not allow trailing commas after the last item. This is the most common error when writing JSON manually:
// Invalid - trailing comma after 30
{"name": "John", "age": 30,}
// Valid - no trailing comma
{"name": "John", "age": 30}
Single Quotes
JSON requires double quotes for strings, not single quotes. JavaScript accepts both, but JSON only accepts double:
// Invalid - single quotes
{'name': 'John'}
// Valid - double quotes only
{"name": "John"}
Unquoted Keys
All keys must be quoted strings, even if they look like valid identifiers:
// Invalid - unquoted key
{name: "John"}
// Valid - quoted key
{"name": "John"}
Comments
Standard JSON does not support comments of any kind. This is a deliberate design decision:
// Invalid - JavaScript-style comment
{
"name": "John" // user name
}
// Invalid - also not allowed
{
/* block comment */
"name": "John"
}
// Valid - no comments, use descriptive key names instead
{"userName": "John"}
Undefined and NaN
JavaScript values undefined, NaN, and Infinity are not valid in JSON:
// Invalid in JSON
{"value": undefined}
{"value": NaN}
{"value": Infinity}
// Use null or omit the key instead
{"value": null}
Advanced Techniques
These approaches handle complex JSON scenarios:
Pretty Printing with Custom Indentation
Control indentation when converting objects to JSON strings:
// JavaScript - 2-space indentation
JSON.stringify(obj, null, 2);
// 4-space indentation
JSON.stringify(obj, null, 4);
// Tab indentation
JSON.stringify(obj, null, "\t");
Handling Large Numbers
JSON numbers can lose precision for very large integers (beyond 2^53). Consider using strings for IDs and large numbers to preserve precision.
Date Handling
JSON has no date type. Common conventions include ISO 8601 strings ("2024-01-15T10:30:00Z") or Unix timestamps (1705314600). Be consistent within your API.
Escaping Special Characters
Strings must escape certain characters: backslash (\\), double quote (\"), and control characters. Most libraries handle this automatically.
Common Mistakes to Avoid
Watch out for these frequent errors when working with JSON:
- Copying from JavaScript: JavaScript objects with unquoted keys and single quotes are not valid JSON. Always validate after copying.
- Adding trailing commas: Common when editing arrays or objects. Remove the comma after the last item.
- Including comments: If you need documentation, use JSON5 or JSONC for development, converting to standard JSON for production.
- Forgetting to escape: Strings containing quotes or backslashes must be escaped. Let libraries handle this.
- Using wrong quotes: Double quotes only. Single quotes, backticks, and smart quotes are all invalid.
Step-by-Step: Debugging Invalid JSON
Follow this process to fix JSON errors:
- Paste into validator: Use the JSON Formatter to identify errors.
- Check the error location: Most validators report the line and position of the first error.
- Look for common issues: Trailing commas, single quotes, unquoted keys, comments.
- Validate incrementally: For large JSON, validate sections to isolate problems.
- Compare with working examples: Reference valid JSON to spot differences.
- Re-validate after each fix: One error can mask others; check after each correction.
JSON vs JavaScript Objects
JSON is stricter than JavaScript object literals. Understanding the differences prevents errors:
- Quoted keys: JSON requires quotes; JavaScript allows unquoted keys that are valid identifiers
- No trailing commas: JSON forbids them; JavaScript allows them
- No comments: JSON has none; JavaScript supports // and /* */
- No undefined: JSON has null but not undefined
- Double quotes only: JSON requires double; JavaScript accepts single
- No functions: JSON is data only; JavaScript objects can contain functions
Working with JSON in Code
JavaScript
// Parse JSON string to JavaScript object
const obj = JSON.parse(jsonString);
// Convert object to JSON string (pretty)
const json = JSON.stringify(obj, null, 2);
// Convert object to JSON string (minified)
const minified = JSON.stringify(obj);
// Handle parsing errors
try {
const data = JSON.parse(userInput);
} catch (error) {
console.error("Invalid JSON:", error.message);
}
Python
import json
# Parse JSON string
data = json.loads(json_string)
# Convert to JSON string (pretty)
json_string = json.dumps(data, indent=2)
# Handle errors
try:
data = json.loads(user_input)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
PHP
// Parse JSON
$data = json_decode($jsonString, true);
// Convert to JSON (pretty)
$json = json_encode($data, JSON_PRETTY_PRINT);
// Check for errors
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}
Related Tools
These tools complement JSON formatting:
- JSON Minifier - Compress JSON by removing whitespace
- JSON to CSV - Convert JSON arrays to CSV format
- Base64 Encode - Encode binary data for JSON transport
- Find and Replace - Make bulk changes to JSON content
Conclusion
Proper JSON formatting and validation prevent errors in API communication, configuration management, and data exchange. Understanding JSON syntax rules, common errors, and debugging techniques makes you more effective at working with this ubiquitous format. The JSON Formatter provides instant validation, beautification, and error detection for any JSON data. Make JSON validation a standard part of your development workflow to catch errors early and ensure your data exchanges work correctly.