JSON for Developers: Basics to Advanced Tricks
JSON for Developers: Basics to Advanced Tricks
JSON became the standard data language of the entire web โ from APIs to config files to document databases.
The Core Structure in 60 Seconds
json
{
"name": "Ahmed",
"age": 30,
"active": true,
"tags": ["dev", "admin"],
"address": { "city": "Riyadh", "zip": "12345" }
}
Golden rules:
- Keys always in double quotes
- Allowed values: string, number, boolean, null, array, object
- No trailing commas โ the last element has no comma
- No comments โ strict JSON supports no // or /* */
Common Errors That Break JSON
| Error | Wrong | Right |
|---|---|---|
| Single quotes | {'a': 1} | {"a": 1} |
| Trailing comma | {"a":1,} | {"a":1} |
| Unquoted key | {a: 1} | {"a": 1} |
| NaN/undefined | {"x": NaN} | {"x": null} |
Format vs Validate vs Minify
- Validate: is the structure valid? Always the first step
- Format: indentation for readability โ for work and Git reviews
- Minify: strip whitespace โ for production (usually saves 30โ40%)
Tricks That Make You Faster
JSON.stringify(obj, null, 2)โ pretty-print with 2-space indentJSON.parse(text, reviver)โ transform values while parsing (dates)[...new Set(arr)]โ dedupe an array in one linestructuredClone(obj)โ deep copies faster than JSON round-trips
JSON Schema โ When Projects Grow
For validating API data at boundaries instead of manual if-else:
json
{
"type": "object",
"properties": { "email": { "type": "string", "format": "email" } },
"required": ["email"]
}
Bottom Line
JSON is simple on the surface and dangerous in the details โ validate before processing, format before reading, minify before shipping.