JSON Formatting Best Practices
JSON (JavaScript Object Notation) is the most common data format on the web. Here's how to work with it without mistakes:
1. Always Validate Before Parsing
Never JSON.parse() untrusted input without a try-catch. A single trailing comma or unquoted key throws a SyntaxError that crashes your app:
try {
const data = JSON.parse(input);
} catch (e) {
console.error("Invalid JSON:", e.message);
}
2. Pretty-Print for Humans, Minify for Machines
During development, always format JSON with 2-space indentation. In production, minify it โ removing whitespace can reduce file size by 30-50%, which matters for large API responses.
3. UTF-8 Only
JSON is defined as UTF-8. Period. If you're seeing ??? in your JSON, you have an encoding mismatch. Always send Content-Type: application/json; charset=utf-8.
4. No Trailing Commas
JSON does not allow trailing commas. {"a":1,} is invalid JSON even though JavaScript allows it. Our JSON Formatter catches this instantly.
5. Always Quote Keys
{a: 1} is valid JavaScript but invalid JSON. JSON requires double quotes: {"a": 1}.
6. Handle Large JSON Efficiently
For files >100MB, don't use JSON.parse โ it loads the entire string into memory. Use a streaming parser like stream-json or oboe.js that processes one token at a time.