What Is JSON? Complete Guide to JSON Formatting
- What Is JSON? Complete Guide to JSON Formatting
- A Brief History and Why JSON Won
- The Six Data Types in JSON
- 1. Objects
- 2. Arrays
- 3. Strings
- 4. Numbers
- 5. Booleans
- 6. Null
- Nesting: Building Complex Structures
- JSON Formatting: Pretty-Print vs. Minified
- Pretty-Printed JSON
- Minified JSON
- Indentation Styles
- Validating JSON: What Makes JSON Invalid
- The Most Common JSON Errors
- JSON vs. XML vs. YAML
- JSON vs. XML
- JSON vs. YAML
- JSON Schema: Enforcing Structure
- Escaping and Unicode in Depth
- Practical Formatting Tips for Developers
- Use a Formatter in Your Editor
- Use a Linter in CI
- Validate Before Parsing in Code
- Prefer Explicit Null Over Missing Keys in APIs
- Watch Out for Date and Time Formatting
- Keep Payload Sizes Reasonable
- Working with JSON Online
- Summary
What Is JSON? Complete Guide to JSON Formatting
JSON — JavaScript Object Notation — is the lingua franca of modern web development. Open any REST API response, peek inside a configuration file, or watch the network traffic of almost any mobile app, and you will find JSON. Despite being named after JavaScript, it is language-agnostic: Python, Go, Rust, Java, PHP, Swift, Kotlin, and dozens of other languages have built-in or first-class libraries for reading and writing it. Understanding JSON deeply — its syntax, its rules, its quirks, and how to format it correctly — is one of the highest-leverage skills a developer can acquire.
This guide covers everything: what JSON is, why it became so dominant, every valid data type, how formatting and minification work, how to validate it, the most common mistakes developers make, how it compares to XML and YAML, and how JSON Schema can help you enforce structure in your own projects.
A Brief History and Why JSON Won
Douglas Crockford formalized JSON in the early 2000s as a lightweight alternative to XML for data interchange between a browser and a server. At the time, AJAX was taking off and developers needed a way to send structured data without the verbosity of XML envelopes. JSON fit the bill perfectly: it mapped directly to JavaScript's built-in object and array literals, so browsers could eval it (unsafely at first, then later parse it properly), and it was far easier to read than angle-bracket soup.
The tipping point came when major APIs — Twitter, Google, Facebook, AWS — either dropped XML or offered JSON as the default format. Today, JSON is not merely popular; it is effectively the default. If you are building or consuming an HTTP API, it will almost certainly speak JSON unless you have a very specific reason to choose something else.
The reasons for this dominance are practical:
- Readability. JSON is easy for humans to scan, especially when pretty-printed.
- Universality. Every modern programming language can parse and produce JSON with minimal friction.
- Simplicity. The grammar fits on a single page. There are no namespaces, no schemas required, no processing instructions.
- Tooling. Every browser, every IDE, and most terminal utilities understand JSON natively.
The Six Data Types in JSON
JSON has exactly six value types. Nothing more, nothing less. This constraint is both a strength and a limitation.
1. Objects
An object is an unordered collection of key-value pairs enclosed in curly braces {}. Keys must be strings (always double-quoted). Values can be any valid JSON type.
{
"name": "Alice",
"age": 30,
"active": true
}A few critical rules apply to objects:
- Keys must be double-quoted strings. Unquoted keys (
{name: "Alice"}) are not valid JSON, even though they are valid JavaScript. - Duplicate keys are technically allowed by the spec, but behavior is undefined — most parsers silently keep the last value, which causes subtle bugs.
- Trailing commas after the final key-value pair are not allowed. This trips up more developers than almost anything else.
2. Arrays
An array is an ordered list of values enclosed in square brackets []. The values can be any valid JSON type and do not need to be homogeneous.
["apple", 42, true, null, {"nested": "object"}, [1, 2, 3]]Arrays preserve insertion order, which makes them the right choice whenever sequence matters. Like objects, arrays do not allow a trailing comma after the last element.
3. Strings
Strings are sequences of Unicode characters enclosed in double quotes. They must use double quotes — single quotes are not valid JSON, even though they are fine in JavaScript.
"Hello, world!"Certain characters inside strings must be escaped with a backslash:
| Character | Escape sequence |
|---|---|
| Double quote | \" |
| Backslash | \\ |
| Newline | \n |
| Carriage return | \r |
| Tab | \t |
| Backspace | \b |
| Form feed | \f |
| Unicode code point | \uXXXX |
Any Unicode character can appear directly in a JSON string as long as it is not a control character. You can also represent any character using its \uXXXX escape form. For characters outside the Basic Multilingual Plane (emoji, for example), JSON uses surrogate pairs: \uD83D\uDE00 for the grinning face emoji.
4. Numbers
JSON numbers cover integers and floating-point values. There is no distinction in the type system between an integer and a float — they are all just "number".
42
3.14159
-7
1.5e10
-2.3E-4Important rules:
- No leading zeros —
07is not valid. - No trailing decimal point —
3.is not valid; you need3.0or just3. - No
NaNorInfinity— these JavaScript values have no JSON equivalent. If you need to represent them, you must usenullor a string like"Infinity"and document the convention. - No hex literals —
0xFFis not valid JSON.
A practical gotcha: JSON numbers are unlimited in theory, but most parsers decode them into IEEE 754 double-precision floats, which can only represent integers exactly up to 2^53. If you are dealing with very large integers (database IDs, snowflake IDs, 64-bit timestamps), transmit them as strings to avoid silent precision loss.
5. Booleans
Booleans are the literal values true and false — always lowercase. True, TRUE, False, and FALSE are all invalid.
{"isVerified": true, "isDeleted": false}6. Null
null represents the intentional absence of a value. It is always lowercase.
{"middleName": null}null is different from a missing key. If a key is present with a null value, the receiver knows the field exists but has no value. If the key is absent entirely, the receiver does not know anything about the field. This distinction matters in APIs: PATCH endpoints often use null to mean "clear this field" and omit a key to mean "leave this field unchanged".
Nesting: Building Complex Structures
Because any value type can appear inside an object or array, JSON can represent arbitrarily deep hierarchies. This is one of its key strengths over flat formats like CSV.
{
"user": {
"id": 1001,
"profile": {
"firstName": "Alice",
"lastName": "Chen",
"address": {
"street": "123 Main St",
"city": "Portland",
"zip": "97201"
}
},
"roles": ["admin", "editor"],
"sessions": [
{"token": "abc123", "expiresAt": "2026-06-10T00:00:00Z"},
{"token": "def456", "expiresAt": "2026-06-15T00:00:00Z"}
]
}
}Deep nesting is powerful but comes with trade-offs. Deeply nested JSON is harder to read, harder to query in code, and can cause issues with some streaming parsers. As a rule of thumb, if you are nesting more than three or four levels deep, consider whether a flatter structure might serve your use case better.
JSON Formatting: Pretty-Print vs. Minified
JSON exists in two presentation modes: pretty-printed (also called beautified or formatted) and minified (also called compacted).
Pretty-Printed JSON
Pretty-printed JSON adds indentation and newlines to make the structure visible:
{
"product": "Widget",
"price": 9.99,
"inStock": true,
"tags": [
"hardware",
"affordable"
]
}When to use pretty-printed JSON:
- Configuration files. Files like
package.json,tsconfig.json, and.prettierrcare read and edited by humans. Pretty-printing makes them maintainable. - Debugging and logging. When you are inspecting an API response or logging structured data, pretty-printed output lets you scan it at a glance.
- Documentation and examples. Any JSON you include in a README, tutorial, or API spec should be formatted for readability.
- Version control diffs. Pretty-printed JSON produces more meaningful git diffs because each key-value pair is on its own line.
Minified JSON
Minified JSON strips all unnecessary whitespace:
{"product":"Widget","price":9.99,"inStock":true,"tags":["hardware","affordable"]}When to use minified JSON:
- API responses in production. Removing whitespace reduces payload size, which reduces bandwidth and latency, especially for mobile clients on constrained networks.
- Cookies and headers. Any JSON stored in a cookie or custom header benefits from being as compact as possible.
- Caching and storage. When persisting large volumes of JSON to disk or a key-value store, minified JSON consumes less space.
A JSON Formatter lets you switch between these modes instantly — paste minified JSON to beautify it for inspection, or paste formatted JSON to minify it before shipping.
Indentation Styles
When pretty-printing, the two common conventions are 2-space indentation (popular in JavaScript and TypeScript communities, used by Prettier by default) and 4-space indentation (popular in Python and Java communities). Tabs are also valid. The choice is purely stylistic — pick one convention per project and stick to it.
Validating JSON: What Makes JSON Invalid
JSON validation is the process of confirming that a string is syntactically correct JSON. This is distinct from schema validation, which checks whether the data matches an expected structure. Syntactic validation is all-or-nothing: either a string parses as valid JSON or it does not.
The Most Common JSON Errors
1. Trailing commas
This is far and away the most frequent mistake, because JavaScript object literals and many configuration formats (JSON5, JSONC, TOML) do allow trailing commas.
{
"name": "Alice",
"age": 30,
}The comma after 30 is invalid. Remove it.
2. Single-quoted strings
Developers who work primarily in JavaScript or Python often reach for single quotes out of habit:
{'name': 'Alice'}Neither the key nor the value is valid here. All strings in JSON must use double quotes.
3. Unquoted keys
Again, valid in JavaScript but not in JSON:
{name: "Alice"}The key name must be written as "name".
4. Comments
JSON has no comment syntax. This surprises many developers who use configuration files that look like JSON but are actually a superset (like JSONC used in VS Code settings, or JSON5).
{
// This is not valid JSON
"name": "Alice"
}If you need to include comments in a JSON-like config file, use a superset format. If you are exchanging data between systems, leave comments out.
5. Unescaped control characters
Raw newlines, tabs, or other control characters inside a string are not valid JSON. They must be escaped:
{"note": "line one\nline two"}6. Using undefined, NaN, or Infinity
These JavaScript values do not exist in JSON. If you see them in a payload, the encoder skipped proper serialization. Use null or a documented string convention instead.
7. Wrong number formats
Leading zeros (042), bare decimals (3.), and hex literals (0x1F) are all invalid.
JSON vs. XML vs. YAML
Three formats dominate structured data interchange. Each has a home field where it excels.
JSON vs. XML
XML was the incumbent that JSON displaced for most API use cases. XML is far more expressive — it supports attributes, namespaces, processing instructions, mixed content (text interspersed with child elements), and a rich ecosystem of standards (XPath, XSLT, XML Schema). For documents that are part data and part narrative — like legal contracts, publishing formats (EPUB, DocBook), or configuration that requires validation — XML remains a solid choice.
For pure data interchange between services, however, JSON wins on almost every axis: it is smaller, faster to parse, easier to read, and maps naturally to the data structures already in your code.
<!-- XML -->
<user>
<name>Alice</name>
<age>30</age>
</user>{"name": "Alice", "age": 30}The JSON version is roughly half the size and immediately obvious to any developer.
JSON vs. YAML
YAML is a superset of JSON (any valid JSON is valid YAML) that adds indentation-based structure, comments, multi-line strings, anchors and aliases, and more. It is enormously popular for configuration files — Kubernetes manifests, GitHub Actions workflows, Docker Compose files, and Ansible playbooks all use YAML.
YAML's strengths over JSON for configuration:
- Comments are supported natively.
- Multi-line strings are readable without escape sequences.
- Anchors (
&) and aliases (*) allow you to reuse values without repetition.
YAML's weaknesses:
- Indentation is significant, so a misplaced space silently changes the document's meaning.
- The spec has several surprising edge cases (the Norway problem:
NOparses asfalsein YAML 1.1; bare numbers can be interpreted as octal). - For machine-to-machine communication, YAML's extra power is unnecessary overhead.
In practice: use JSON for API payloads and programmatic data exchange, YAML for human-edited configuration files where comments and readability matter most.
JSON Schema: Enforcing Structure
JSON Schema is a vocabulary for describing and validating the structure of JSON documents. It is itself written in JSON, which makes it self-referential and toolable.
A simple schema for a user object:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"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
}
},
"additionalProperties": false
}With this schema you can:
- Confirm that required fields are present.
- Enforce type constraints —
idmust be an integer, not a string. - Set range constraints on numbers.
- Reject unexpected extra fields when
additionalPropertiesis false. - Document the shape of your data in a machine-readable way that IDEs can use for autocomplete and inline validation.
JSON Schema is supported by validation libraries in every major language and by API specification formats like OpenAPI 3.x (which embeds JSON Schema inline). Adding schemas to your project catches data contract violations early — at development time rather than in production.
Escaping and Unicode in Depth
JSON strings are Unicode strings. The spec requires that parsers support the full Unicode character set, though it permits implementations to restrict the encoding of the serialized bytes to UTF-8, UTF-16, or UTF-32. In practice, UTF-8 is universal.
When you need to represent a character that is difficult to type or transmit safely, use the \uXXXX escape. Each \uXXXX represents a single UTF-16 code unit. For code points in the Basic Multilingual Plane (U+0000 through U+FFFF), a single \uXXXX is sufficient:
{"currency": "\u20AC"}That is the Euro sign €.
For supplementary characters (code points above U+FFFF), JSON requires a surrogate pair — two consecutive \uXXXX escapes representing the high and low surrogates:
{"emoji": "\uD83D\uDE00"}Most modern parsers handle this transparently, but if you are implementing a custom parser or working with a language that distinguishes between BMP and supplementary characters, be aware of it.
A practical concern: when JSON is embedded inside HTML or transmitted through systems that interpret certain characters specially, you may want to escape characters like <, >, &, and / to their \uXXXX forms to prevent XSS or injection issues. < becomes \u003C, > becomes \u003E, and & becomes \u0026.
Practical Formatting Tips for Developers
Use a Formatter in Your Editor
Every major editor has a JSON formatter built in or available as an extension. VS Code's built-in formatter handles JSON with Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac). Configure your editor to format JSON on save so you never commit malformed JSON.
Use a Linter in CI
Add jsonlint or a similar tool to your CI pipeline to catch malformed JSON files before they reach production. Configuration files like package.json, API mock fixtures, and translation files are especially prone to hand-editing mistakes.
Validate Before Parsing in Code
When consuming JSON from an external source — a third-party API, user uploads, a webhook — always validate before you parse and process. A try/catch around JSON.parse() gives you syntactic validation. Schema validation with a library like ajv (JavaScript), jsonschema (Python), or serde with derive macros (Rust) gives you semantic validation.
Prefer Explicit Null Over Missing Keys in APIs
When designing API responses, be consistent about whether an absent value is represented as a missing key or as null. Mixing the two conventions forces clients to handle both cases and leads to bugs. Pick one convention and document it.
Watch Out for Date and Time Formatting
JSON has no built-in date or time type. The convention is to use ISO 8601 strings: "2026-06-04T15:30:00Z". Avoid Unix timestamps as numbers for anything human-facing, and be explicit about time zones — Z for UTC, or an offset like +05:30.
Keep Payload Sizes Reasonable
For API responses, aim to return only the data the client needs. Deeply nested objects with dozens of fields are harder to parse, harder to cache, and slower to transmit. Pagination, field selection (?fields=id,name), and sparse fieldsets are standard techniques for keeping payloads lean.
Working with JSON Online
For quick tasks — validating an API response you just copied, formatting a minified blob, or checking whether a config file is well-formed — an in-browser tool is the fastest option. The JSON Formatter on this site runs entirely in your browser: no data is sent to any server, nothing is logged, and you do not need to sign up for anything. Paste your JSON, click format, and you get back a validated, indented result or a clear error message pointing to the exact line and character where the syntax breaks.
This is especially useful when:
- You receive a minified API response and want to inspect its structure.
- You are writing JSON by hand and want to confirm it is valid before committing.
- You want to minify formatted JSON before embedding it in a script or environment variable.
- You are debugging a webhook payload and need to see its shape quickly.
Summary
JSON is simple by design. Six types, a small grammar, no ambiguity — and that simplicity is precisely why it became the default data format for the web. Understanding the rules deeply means fewer bugs at the boundaries of your systems: invalid payloads that fail silently, precision loss in large integers, encoding errors that corrupt data in transit, or trailing commas that break a parser in production.
The key takeaways from this guide:
- JSON has six types: object, array, string, number, boolean, and null.
- Keys must be double-quoted strings; single quotes and unquoted keys are invalid.
- Trailing commas, comments, and
NaN/Infinityare not allowed in standard JSON. - Pretty-print for humans; minify for machines.
- Use JSON Schema to enforce structure and document your data contracts.
- For supplementary Unicode characters, JSON uses surrogate pairs.
- Use ISO 8601 strings for dates and times; transmit large integers as strings.
When you need a fast, private way to format or validate JSON, the JSON Formatter is always available — no install, no account, no data leaving your browser.
You might also like
How to View CSV & Excel Files Online for Free
How to View CSV & Excel Files Online for Free Spreadsheet files are everywhere. Data exports from da…
Read moreHow to Analyze Any File Online: Format & Metadata Guide
How to Analyze Any File Online: Format & Metadata Guide Every file on your computer carries more inf…
Read moreAPI Client Guide: Test APIs Online Without Postman
API Client Guide: Test APIs Online Without Postman Testing an API should be fast and frictionless. Y…
Read more