JSON (JavaScript Object Notation) is the most widely used data-interchange format on the internet today. Whether you're calling a REST API, storing configuration files, or sending data between microservices, JSON is almost certainly involved. Yet despite being ubiquitous, many developers don't fully understand its nuances, limitations, and best practices.
This guide covers everything you need to know about JSON — from the basics of its syntax to advanced topics like schema validation and performance considerations.
What is JSON?
JSON is a lightweight, text-based format for representing structured data. It was derived from JavaScript object literal syntax but is completely language-independent. Virtually every programming language — Python, Java, Go, Ruby, PHP, Rust — has first-class JSON support built in or available through standard libraries.
JSON was formally specified by Douglas Crockford in the early 2000s and later standardized as ECMA-404 and RFC 8259. The format's simplicity and human readability made it rapidly replace XML as the preferred format for web APIs.
JSON Syntax Rules
JSON has only six data types:
1. String — Text enclosed in double quotes: "Hello, World"
2. Number — Integer or floating-point: 42, 3.14, -7, 1.5e10
3. Boolean — true or false (lowercase only)
4. Null — null (representing absence of value)
5. Object — Unordered collection of key-value pairs: {"key": "value"}
6. Array — Ordered list of values: [1, "two", true]
Key rules to remember:
- Keys in objects must always be double-quoted strings (single quotes are not valid JSON)
- Trailing commas after the last element are not allowed in standard JSON
- Comments (// or /* */) are not part of the JSON spec
- Numbers cannot have leading zeros (except 0.5)
- NaN and Infinity are not valid JSON number values
JSON vs XML: Why JSON Won
Before JSON became dominant, XML was the standard for data exchange. Here's why JSON displaced it:
Verbosity: XML requires opening and closing tags for every element, making documents significantly larger. A JSON object {"name":"Alice","age":30} requires 25 bytes; the XML equivalent requires over 60 bytes.
Parsing speed: JSON parsers are simpler and faster than XML parsers because the grammar is less complex.
Native JavaScript compatibility: JSON maps directly to JavaScript objects, eliminating the need for DOM parsing when working in browsers.
Readability: JSON's curly-brace syntax is more compact and intuitive for most developers.
XML still has legitimate uses — particularly when document metadata, namespacing, or mixed content (text interleaved with markup) is needed. But for API responses and configuration, JSON is superior.
Common JSON Use Cases
REST API responses: Almost every modern web API returns JSON. When you call fetch("https://api.example.com/user/1"), you'll get back a JSON object describing the user.
Configuration files: Tools like ESLint (.eslintrc.json), TypeScript (tsconfig.json), and npm (package.json) use JSON for configuration. Note: many tools support JSONC (JSON with Comments) as an extension.
Local storage: Browsers' localStorage API stores strings only, so developers use JSON.stringify() to serialize objects and JSON.parse() to deserialize them.
Inter-service communication: In microservice architectures, services communicate via JSON-encoded messages published to message queues (Kafka, RabbitMQ) or passed over HTTP.
NoSQL databases: Databases like MongoDB store documents as BSON (Binary JSON), and Firestore, CouchDB, and DynamoDB all use JSON-compatible document models.
JSON Schema: Enforcing Structure
JSON by itself has no enforcement of structure. A field expected to be a number could come back as a string, causing runtime errors. JSON Schema (jsonschema.org) solves this by allowing you to define the expected shape of a JSON document.
Example schema for a user object:
{
"$schema": "https://json-schema.org/draft-07/schema",
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": { "type": "integer", "minimum": 1 },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0, "maximum": 150 }
}
}JSON Schema supports Draft-07 and Draft-2020-12. Validators are available for Node.js (ajv), Python (jsonschema), Java (everit), and more.
Performance Tips
Minify for production: Remove whitespace before sending JSON over the network. A formatter adds indentation for readability in development; minification reverses this for production. Even small JSON payloads add up at scale.
Avoid deeply nested structures: Each layer of nesting adds parsing complexity and makes the schema harder to reason about. Prefer flat structures when possible.
Use streaming for large payloads: If you're processing JSON files larger than a few MB, don't load them all into memory. Use streaming parsers like oboe.js (browser) or Node.js's JSONStream.
Prefer integers over strings for identifiers: {"userId": 12345} is more efficient than {"userId": "12345"} both in size and type-checking overhead.
Security Considerations
Never use eval() to parse JSON: Calling eval('(' + jsonString + ')') in JavaScript executes arbitrary code. Always use JSON.parse().
Validate and sanitize user input: If user-provided JSON is stored or processed, validate it against a schema first. Maliciously crafted JSON can exploit poorly written parsers.
Prototype pollution: In JavaScript, setting a key like __proto__ in a parsed JSON object can pollute the Object prototype. Use libraries that protect against this, or freeze prototypes in security-sensitive code.
JSON injection: If you're embedding JSON inside HTML (e.g., SSR), ensure <, >, and & are escaped to prevent XSS attacks.