What is JSON?
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format that's easy for humans to read and write, and easy for machines to parse and generate. Despite its name, JSON is language-independent and is used extensively across all modern programming languages.
JSON has become the de facto standard for data exchange on the web, particularly for REST APIs, configuration files, and storing structured data in databases like MongoDB.
JSON Syntax Rules
JSON has simple but strict syntax rules that must be followed:
Data Types
- Strings: Must be in double quotes ("text")
- Numbers: Integer or floating point (42, 3.14, -17)
- Booleans: true or false (lowercase)
- Null: null (lowercase)
- Arrays: Ordered lists in square brackets [1, 2, 3]
- Objects: Key-value pairs in curly braces {"key": "value"}
Common Mistakes
- Trailing commas: {"a": 1,} is invalid—no comma after last item
- Single quotes: {'key': 'value'} is invalid—must use double quotes
- Unquoted keys: {key: "value"} is invalid—keys must be quoted
- Comments: // or /* */ are not allowed in JSON
- Undefined: undefined is not a valid JSON value
JSON vs Other Formats
JSON vs XML
JSON is generally preferred over XML for most modern applications because it's more compact, easier to read, and faster to parse. XML has more features (attributes, namespaces, comments) but at the cost of verbosity.
JSON vs YAML
YAML is a superset of JSON that allows comments and more human-friendly syntax. YAML is popular for configuration files, while JSON is preferred for data exchange due to its simplicity and universal support.
Working with JSON in JavaScript
JavaScript provides built-in methods for working with JSON:
// Parse JSON string to object
const data = JSON.parse('{"name":"John"}');
// Convert object to JSON string
const json = JSON.stringify({name: "John"});
// Pretty print with 2-space indent
const pretty = JSON.stringify(data, null, 2);JSON Best Practices
- Use consistent naming: camelCase or snake_case, but be consistent
- Keep it flat: Avoid deeply nested structures when possible
- Use arrays for ordered collections: When order matters
- Include ISO 8601 dates: "2024-03-14T12:00:00Z"
- Validate input: Always validate JSON from external sources
- Handle errors gracefully: Wrap JSON.parse in try-catch
JSON in APIs
JSON is the standard format for REST APIs. When working with APIs:
- Set the Content-Type header to application/json
- Use JSON.stringify() when sending data
- Handle HTTP error responses properly
- Validate response structure before using data
Performance Considerations
For large JSON files, consider:
- Streaming parsers: For files too large for memory
- Minification: Remove whitespace to reduce transfer size
- Compression: Use gzip for network transfer
- Pagination: Split large arrays into smaller chunks