What is JSON?
JSON, short for JavaScript Object Notation, is a lightweight data interchange format that has become the backbone of modern web development. Originally derived from JavaScript, JSON is now language-independent and supported by virtually every programming language in use today, from Python and Java to Go and Rust.
At its core, JSON represents data using two fundamental structures: objects (collections of key-value pairs enclosed in curly braces) and arrays (ordered lists of values enclosed in square brackets). Values can be strings, numbers, booleans, null, objects, or arrays, allowing you to model complex, nested data with ease.
JSON gained popularity because of its simplicity. Unlike XML or other markup languages, JSON is easy for humans to read and write, and easy for machines to parse and generate. This balance makes it the default choice for REST APIs, configuration files, and data storage in modern applications.
JSON Syntax Rules
While JSON looks straightforward, its specification is strict. Breaking any of these rules will result in a parse error. Here are the key rules every developer must follow:
- Keys must be strings. Every key in a JSON object must be wrapped in double quotes. Single quotes are not valid. For example,
{"name": "Alice"}is correct, but{name: "Alice"}is not. - No trailing commas. A comma after the last element in an object or array will cause a parse error. This is one of the most common mistakes developers make when hand-editing JSON.
- No comments. The JSON specification does not support comments of any kind, whether single-line (
//) or multi-line (/* */). If you need to annotate your data, consider using a key like"_comment"or switching to a format like JSON5. - Strings must use double quotes. Single quotes, backticks, and unquoted strings are all invalid in JSON. Only double-quoted strings are accepted.
- Numbers cannot have leading zeros. Writing
007is invalid; use7instead. Decimal numbers must have a digit before the decimal point, so.5should be written as0.5.
Here is an example of well-formed JSON:
{
"user": {
"id": 1,
"name": "Alice",
"email": "[email protected]",
"active": true,
"roles": ["admin", "editor"],
"preferences": null
}
}
Formatting vs Minifying
Formatting (also called "pretty-printing") adds indentation, newlines, and spacing to JSON so that it is easier for humans to read. This is essential during development, debugging, and code review. Most editors and online tools let you format JSON with two or four spaces of indentation.
Minifying does the opposite: it strips all unnecessary whitespace to produce the smallest possible output. Minified JSON is what you want in production environments, API responses, and anywhere file size and bandwidth matter. A minified version of the object above would look like this:
{"user":{"id":1,"name":"Alice","email":"[email protected]","active":true,"roles":["admin","editor"],"preferences":null}}
In JavaScript, you control this with JSON.stringify(). Calling JSON.stringify(data, null, 2) produces formatted output with two-space indentation, while JSON.stringify(data) without the third argument produces minified output. Use formatted JSON for logs and debugging, and minified JSON for network transfer and storage.
Common JSON Errors and How to Fix Them
Even experienced developers run into JSON parsing errors. Here are the most frequent culprits and how to resolve them:
- Trailing comma: Remove the comma after the last property in an object or the last element in an array. For example,
{"a": 1, "b": 2,}is invalid. - Single quotes: Replace all single quotes with double quotes. Many languages allow single-quoted strings, but JSON does not.
- Unquoted keys: Wrap every key in double quotes. Shorthand like
{name: "Alice"}works in JavaScript objects but not in JSON. - Unescaped special characters: Characters like backslashes, tabs, and newlines inside strings must be escaped. Use
\\,\t, and\nrespectively. - Wrong data type: JSON values of
undefinedare not valid. Usenullinstead. Also,NaNandInfinityare not permitted in JSON. - BOM or invisible characters: Copying JSON from word processors or certain web pages can introduce invisible characters. Paste your JSON into a plain-text editor or validation tool to strip them out.
When you encounter a parse error, the fastest fix is to paste your JSON into a dedicated validator that highlights the exact line and character position of the issue.
JSON vs XML
JSON and XML both serve as data interchange formats, but they differ in significant ways. Understanding these differences helps you choose the right format for your project.
- Verbosity: XML requires opening and closing tags for every element, making it significantly more verbose than JSON. A simple name-value pair like
{"name": "Alice"}becomes<name>Alice</name>in XML. - Data types: JSON natively supports strings, numbers, booleans, null, arrays, and objects. XML treats everything as text; you need schemas (XSD) to enforce data types.
- Readability: For simple data structures, JSON is easier to scan at a glance. XML can become deeply nested and harder to follow.
- Parsing: JSON maps directly to native data structures in most languages (dictionaries, maps, arrays). XML requires a dedicated parser and often an additional step to convert the DOM into usable objects.
- Features: XML supports attributes, namespaces, XSLT transformations, and XPath queries. JSON has none of these, which makes it simpler but less powerful for document-centric use cases.
In practice, JSON dominates REST APIs and modern web services, while XML remains common in enterprise systems, SOAP web services, and document formats like SVG and XHTML.
JSON in APIs
JSON is the standard format for request and response bodies in REST APIs. Following consistent formatting conventions makes your APIs easier to consume and debug.
Request headers: Always set Content-Type: application/json when sending JSON in a request body. For responses, the server should return the same content type so that clients know how to parse the body.
Naming conventions: Most JSON APIs use camelCase for keys (e.g., firstName, createdAt). Some ecosystems, particularly those influenced by Python, prefer snake_case (e.g., first_name, created_at). The key is to be consistent within your API.
Envelope patterns: Many APIs wrap their responses in a standard envelope that includes metadata alongside the data. A typical pattern looks like this:
{
"status": "success",
"data": {
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
},
"meta": {
"page": 1,
"total": 42
}
}
Error responses: When an API returns an error, it should still return valid JSON. A common convention includes a machine-readable error code, a human-readable message, and optionally a details array for validation errors:
{
"status": "error",
"error": {
"code": "VALIDATION_FAILED",
"message": "Invalid request body",
"details": [
{ "field": "email", "issue": "must be a valid email address" }
]
}
}
Following these conventions ensures that your API is predictable and easy to integrate with, regardless of the client language or framework.