Why Formatting Matters
JSON has become the universal language of data exchange. Every modern API, configuration file, and database document speaks it. But writing valid JSON is not the same as writing good JSON. Poorly formatted data leads to bugs that are hard to trace, APIs that frustrate consumers, and config files that no one wants to maintain.
Well-formatted JSON is easier to read during code review, simpler to debug when something breaks, and more predictable for the systems that consume it. Whether you are designing a public REST API or writing a package.json by hand, the formatting choices you make today will save (or cost) hours of developer time down the road.
This guide covers every aspect of JSON formatting, from indentation and naming conventions to data structure patterns and common pitfalls. Each section includes practical, copy-pasteable code examples showing the wrong way and the right way, so you can apply these practices immediately.
Indentation and Whitespace
Indentation is the most visible formatting decision you will make. It affects readability for humans and file size for machines. There are four common approaches, and each one has a place.
2-Space Indentation
The most popular choice for configuration files and source-controlled JSON. It is compact enough to keep deeply nested structures readable without excessive horizontal scrolling.
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.0",
"lodash": "^4.17.21"
}
}Best for: package.json, tsconfig.json, .eslintrc.json, and any JSON committed to version control.
4-Space Indentation
Provides more visual separation between nesting levels. Some teams prefer this for data files that are frequently read by humans, such as fixture data or test snapshots.
{
"user": {
"id": 42,
"name": "Alice Johnson",
"address": {
"street": "123 Main St",
"city": "Springfield",
"state": "IL"
}
}
}Best for: Data files where readability is the top priority, documentation examples, and teams that already use 4-space indentation in their code.
Tab Indentation
Tabs allow each developer to configure their preferred visual width in their editor. However, tabs are rare in JSON files and can cause inconsistencies across tools.
{
"setting": "value",
"nested": {
"deep": true
}
}Best for: Projects where the team already uses tabs everywhere and wants consistency across file types. In practice, most JSON tooling defaults to spaces.
Minified (No Whitespace)
Strips all unnecessary whitespace, producing the smallest possible payload. This is what your API should return in production.
{"name":"my-project","version":"1.0.0","dependencies":{"express":"^4.18.0","lodash":"^4.17.21"}}Best for: API responses, data sent over the network, stored payloads in databases, and any context where file size matters more than human readability.
Recommendation
Use 2-space indentation for files that humans will read and edit. Use minified JSON for data transmitted over the network. Configure your formatter once and automate it. In JavaScript, this is as simple as:
// Pretty-print with 2 spaces
JSON.stringify(data, null, 2);
// Minify for production
JSON.stringify(data);Naming Conventions
Inconsistent key names are one of the most common sources of frustration when working with JSON. There are four major conventions, and real-world APIs use all of them.
camelCase
Starts with a lowercase letter, capitalizes the first letter of each subsequent word. This is the natural style for JavaScript and TypeScript developers.
{
"firstName": "Alice",
"lastName": "Johnson",
"emailAddress": "[email protected]",
"phoneNumber": "+1-555-0100",
"isActive": true
}Used by: Google APIs, Firebase, most JavaScript-based services.
snake_case
All lowercase with underscores between words. Popular in Python and Ruby ecosystems, and widely used by APIs that prioritize readability over JavaScript conventions.
{
"first_name": "Alice",
"last_name": "Johnson",
"email_address": "[email protected]",
"phone_number": "+1-555-0100",
"is_active": true
}Used by: GitHub API, Stripe API, Twitter/X API, most Python-based services.
kebab-case
All lowercase with hyphens between words. Less common in JSON because hyphens require bracket notation in JavaScript (obj["first-name"] instead of obj.firstName).
{
"first-name": "Alice",
"last-name": "Johnson",
"email-address": "[email protected]"
}Used by: Some configuration files (CSS-in-JS configs, HTTP headers). Generally avoided in APIs because of the bracket notation requirement.
PascalCase
Every word starts with an uppercase letter. Common in .NET and C# ecosystems.
{
"FirstName": "Alice",
"LastName": "Johnson",
"EmailAddress": "[email protected]",
"IsActive": true
}Used by: Microsoft Graph API, Azure APIs, .NET-based services.
The Golden Rule: Consistency
The worst naming convention is an inconsistent one. This is what you should never do:
BAD: Mixed conventions in the same object
{
"firstName": "Alice",
"last_name": "Johnson",
"Email-Address": "[email protected]",
"PhoneNumber": "+1-555-0100",
"is_active": true
}GOOD: One convention used everywhere
{
"first_name": "Alice",
"last_name": "Johnson",
"email_address": "[email protected]",
"phone_number": "+1-555-0100",
"is_active": true
}Pick one convention for your project and enforce it. If you are building a JavaScript-first product,camelCase is the natural fit. If your API consumers span multiple languages,snake_case tends to be the most universally readable. Document your choice and stick with it.
Choosing the Right Data Types
JSON gives you six data types: string, number, boolean, null, object, and array. Using the wrong type for a field is a surprisingly common mistake that creates headaches for everyone consuming your data.
Strings vs Numbers for IDs
BAD: Numeric IDs that might exceed JavaScript's safe integer limit
{
"tweet_id": 1352856348293849600,
"user_id": 9007199254740993
}JavaScript's Number.MAX_SAFE_INTEGER is 9007199254740991. IDs larger than this will lose precision when parsed. This is a real bug that has affected Twitter, Snowflake, and other systems that use 64-bit integer IDs.
GOOD: String IDs that are always safe
{
"tweet_id": "1352856348293849600",
"user_id": "9007199254740993"
}Rule of thumb: If you will never do arithmetic on a value, make it a string. IDs, phone numbers, zip codes, and UUIDs should all be strings.
Booleans vs String "true"/"false"
BAD: Boolean values encoded as strings
{
"is_active": "true",
"has_verified_email": "false",
"allow_notifications": "yes"
}String "false" is truthy in JavaScript: if ("false") evaluates to true. This is one of the most common sources of boolean-related bugs.
GOOD: Native boolean values
{
"is_active": true,
"has_verified_email": false,
"allow_notifications": true
}Arrays vs Comma-Separated Strings
BAD: Lists stored as comma-separated strings
{
"tags": "javascript,react,typescript",
"permissions": "read,write,delete"
}This forces every consumer to split the string, handle edge cases (trailing commas, spaces), and lose type safety. It also makes it impossible to store values that contain commas.
GOOD: Native arrays
{
"tags": ["javascript", "react", "typescript"],
"permissions": ["read", "write", "delete"]
}Numbers vs Stringified Numbers
BAD: Numeric values stored as strings
{
"price": "29.99",
"quantity": "5",
"rating": "4.5"
}GOOD: Actual numbers when arithmetic is expected
{
"price": 29.99,
"quantity": 5,
"rating": 4.5
}Use numbers when the value will be used in calculations. Use strings when the value is an identifier or label that happens to contain digits (zip codes, phone numbers, version strings).
Structuring Your Data
How you organize fields within a JSON object can make the difference between a pleasure and a nightmare. Good structure groups related data, avoids unnecessary nesting, and makes the object self-documenting.
Flat vs Nested Objects
BAD: A flat mess with no grouping
{
"user_id": "u_12345",
"user_first_name": "Alice",
"user_last_name": "Johnson",
"user_email": "[email protected]",
"user_avatar_url": "https://cdn.example.com/alice.jpg",
"user_address_street": "123 Main St",
"user_address_city": "Springfield",
"user_address_state": "IL",
"user_address_zip": "62701",
"user_pref_theme": "dark",
"user_pref_language": "en",
"user_pref_notifications_email": true,
"user_pref_notifications_sms": false,
"user_created_at": "2025-01-15T08:30:00Z",
"user_updated_at": "2026-02-10T14:22:00Z",
"user_last_login": "2026-02-10T09:00:00Z"
}Every field has the user_ prefix baked in, the address is split across four separate keys, and preferences are scattered. It is hard to tell where one group ends and another begins.
GOOD: Logical grouping with nested objects
{
"id": "u_12345",
"profile": {
"first_name": "Alice",
"last_name": "Johnson",
"email": "[email protected]",
"avatar_url": "https://cdn.example.com/alice.jpg"
},
"address": {
"street": "123 Main St",
"city": "Springfield",
"state": "IL",
"zip": "62701"
},
"preferences": {
"theme": "dark",
"language": "en",
"notifications": {
"email": true,
"sms": false
}
},
"metadata": {
"created_at": "2025-01-15T08:30:00Z",
"updated_at": "2026-02-10T14:22:00Z",
"last_login": "2026-02-10T09:00:00Z"
}
}The grouped version is easier to scan, documents itself through its structure, and makes it simple to pass sections around independently (e.g., pass just the address object to a shipping function).
Denormalization vs References
Denormalized: Data duplicated for convenience
{
"order_id": "ord_001",
"product_name": "Wireless Keyboard",
"product_price": 49.99,
"product_category": "Electronics",
"customer_name": "Alice Johnson",
"customer_email": "[email protected]"
}Normalized: References to other entities
{
"order_id": "ord_001",
"product_id": "prod_555",
"customer_id": "u_12345",
"quantity": 1,
"total": 49.99
}Use denormalized data when consumers need a complete view without follow-up requests (e.g., a mobile app displaying an order summary). Use references when data freshness matters and consumers can make additional requests. Many APIs offer both through query parameters like ?expand=customer,product.
Consistent Array Item Shape
BAD: Array items with different shapes
{
"results": [
{ "id": 1, "name": "Alice", "type": "admin" },
{ "id": 2, "display_name": "Bob" },
{ "id": 3, "name": "Charlie", "type": "user", "extra_field": true }
]
}GOOD: Every item has the same fields
{
"results": [
{ "id": 1, "name": "Alice", "type": "admin" },
{ "id": 2, "name": "Bob", "type": "user" },
{ "id": 3, "name": "Charlie", "type": "user" }
]
}Handling Dates and Numbers
Dates and numbers are the two areas where JSON formatting mistakes cause the most production bugs. JSON has no native date type, and its number type has well-known precision limits.
Dates: Use ISO 8601
BAD: Ambiguous date formats
{
"created": "02/10/2026",
"updated": "10 Feb 2026",
"expires": "2026.02.10"
}Is "02/10/2026" February 10th or October 2nd? It depends on whether you are American or European. Free-form date strings are a guaranteed source of bugs.
GOOD: ISO 8601 with timezone
{
"created_at": "2026-02-10T08:30:00Z",
"updated_at": "2026-02-10T14:22:00+05:30",
"expires_at": "2026-12-31T23:59:59Z"
}ISO 8601 is unambiguous, sortable as a string, and supported by every date library in every language. Always include the timezone. Use Z for UTC.
When to Use Unix Timestamps
{
"event_time": 1770681000,
"event_time_ms": 1770681000000
}Unix timestamps are useful when you need to do fast arithmetic (e.g., "how many seconds until expiry?") or when you are working with systems that natively use epoch time (logs, metrics, caching headers). Always document whether your timestamps are in seconds or milliseconds.
Currency: Integers Over Floats
BAD: Floating point currency
{
"subtotal": 19.99,
"tax": 1.60,
"total": 21.59
}This looks correct, but floating point arithmetic can produce surprises:
// In JavaScript:
0.1 + 0.2 === 0.30000000000000004 // true
19.99 + 1.60 === 21.590000000000003 // trueGOOD: Currency in smallest unit (cents)
{
"subtotal_cents": 1999,
"tax_cents": 160,
"total_cents": 2159,
"currency": "USD"
}Stripe, Square, and most payment processors use this pattern. Integer arithmetic is exact. Always include the currency code so consumers know what unit they are working with.
Percentages
BAD: Ambiguous percentage representation
{
"tax_rate": 8.25,
"discount": 15
}Is tax_rate 8.25% or 825%? Is discount 15% or $15?
GOOD: Explicit representation
{
"tax_rate_percent": 8.25,
"discount_percent": 15,
"completion_ratio": 0.75
}Include the unit in the field name, or document whether the value is a percentage (8.25 meaning 8.25%) or a ratio (0.0825 meaning 8.25%). Pick one convention and stick with it across your entire API.
Nulls, Defaults, and Missing Fields
How you handle missing or empty data in JSON has a bigger impact on API usability than most people realize. There are several options, and each communicates a different meaning.
null vs Empty String vs Omitting the Field
// Option 1: Explicit null (field exists, value is intentionally absent)
{
"middle_name": null,
"deleted_at": null
}
// Option 2: Empty string (field exists, value is empty text)
{
"middle_name": "",
"bio": ""
}
// Option 3: Omit the field entirely (field is not applicable)
{
"first_name": "Alice",
"last_name": "Johnson"
// middle_name is simply not present
}When to Use Each Approach
null: The field is a recognized part of the schema, but it has no value right now. Example:"deleted_at": nullmeans the record has not been deleted.- Empty string
"": The user explicitly provided an empty value. Example: a user cleared their bio field. Only use for string fields. - Omit the field: The field is not relevant in this context. Example: a guest user object does not include
subscription_planbecause guests do not have subscriptions.
API Response Pattern: Consistent Shape
BAD: Shape changes depending on data availability
// Response when user has a phone:
{
"name": "Alice",
"phone": "+1-555-0100"
}
// Response when user has no phone:
{
"name": "Bob"
// phone is just... gone
}Consumers now need to check if ("phone" in user) instead of just checking the value. This is fragile and error-prone.
GOOD: All fields always present with null for absent values
// Response when user has a phone:
{
"name": "Alice",
"phone": "+1-555-0100"
}
// Response when user has no phone:
{
"name": "Bob",
"phone": null
}A consistent shape makes it easy to write typed interfaces in TypeScript or define JSON Schema validations. Consumers always know what fields to expect.
Default Values in Responses
{
"theme": "light",
"language": "en",
"items_per_page": 25,
"notifications_enabled": true
}When a user has not explicitly set a preference, return the default value rather than null. This way, the client does not need to maintain its own copy of default values.
Working with Large JSON Files
As datasets grow, naive JSON handling breaks down. A 500 MB JSON array will crash a browser tab and consume gigabytes of memory during parsing. Here are proven patterns for handling large data.
Pagination
Never return unbounded collections. Always paginate.
Cursor-based pagination (preferred)
{
"data": [
{ "id": "item_100", "name": "Item 100" },
{ "id": "item_101", "name": "Item 101" }
],
"pagination": {
"next_cursor": "eyJpZCI6MTAxfQ==",
"has_more": true,
"per_page": 50
}
}Offset-based pagination (simpler but less efficient)
{
"data": [
{ "id": 100, "name": "Item 100" },
{ "id": 101, "name": "Item 101" }
],
"pagination": {
"total": 10432,
"page": 3,
"per_page": 50,
"total_pages": 209
}
}JSON Lines (NDJSON) for Streaming
When dealing with very large datasets, consider newline-delimited JSON (NDJSON). Each line is a standalone JSON object, so consumers can process records one at a time without loading the entire file into memory.
{"id": 1, "event": "page_view", "timestamp": "2026-02-10T08:00:00Z"}
{"id": 2, "event": "click", "timestamp": "2026-02-10T08:00:01Z"}
{"id": 3, "event": "purchase", "timestamp": "2026-02-10T08:00:05Z"}NDJSON is used by Elasticsearch bulk APIs, BigQuery exports, and many logging systems. A 1 GB NDJSON file can be processed with constant memory usage because you read one line at a time.
Keeping Payloads Small
- Use field selection: Let consumers request only the fields they need.
GET /users?fields=id,name,emailinstead of returning everything. - Compress responses: Enable gzip or Brotli compression. A typical JSON API response compresses by 70-90%. A 100 KB payload drops to 10-30 KB.
- Avoid embedding binary data: Base64-encoded images or files inflate payloads by ~33%. Use URLs instead and let clients fetch binary data separately.
- Trim unnecessary precision:
3.14is often sufficient instead of3.141592653589793. Round to the precision your consumers actually need.
Payload Size Reference
To give you a sense of scale for typical JSON payloads:
- 1 KB: A single user profile with 15-20 fields
- 10 KB: A product listing with 50 items (name, price, thumbnail URL)
- 100 KB: A full page of search results with detailed metadata
- 1 MB: Approaching the limit for comfortable mobile performance
- 10 MB+: Consider pagination, streaming, or a different approach entirely
JSON in API Design
When designing APIs that speak JSON, formatting decisions affect every consumer of your service. Consistent patterns reduce onboarding time and make your API predictable.
The Envelope Pattern
Wrap your responses in a standard envelope so consumers always know where to find the data, errors, and metadata.
Successful response:
{
"data": {
"id": "u_12345",
"name": "Alice Johnson",
"email": "[email protected]"
},
"meta": {
"request_id": "req_abc123",
"response_time_ms": 42
}
}Error response:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request body contains invalid fields.",
"details": [
{
"field": "email",
"message": "Must be a valid email address.",
"received": "not-an-email"
},
{
"field": "age",
"message": "Must be a positive integer.",
"received": -5
}
]
},
"meta": {
"request_id": "req_def456",
"response_time_ms": 12
}
}Consistent Error Format
Every error your API returns should follow the same structure. Consumers should never have to guess whether the error details are in error.message, errors[0].msg, or detail.
BAD: Inconsistent error shapes
// Endpoint A
{ "error": "Not found" }
// Endpoint B
{ "errors": [{ "msg": "Invalid input" }] }
// Endpoint C
{ "message": "Unauthorized", "statusCode": 401 }GOOD: One error format everywhere
{
"error": {
"code": "NOT_FOUND",
"message": "The requested resource was not found.",
"details": []
}
}HATEOAS Links
Include links to related resources so consumers can navigate your API without hardcoding URLs.
{
"data": {
"id": "ord_789",
"status": "shipped",
"total_cents": 4999
},
"links": {
"self": "/api/v2/orders/ord_789",
"customer": "/api/v2/customers/u_12345",
"invoice": "/api/v2/orders/ord_789/invoice",
"tracking": "https://tracking.example.com/TRACK123"
}
}Versioning
When your JSON response format changes, consumers need a way to opt in to the new version. Common approaches include putting the version in the URL (/api/v2/users) or in a header (Accept: application/vnd.myapp.v2+json). Whichever you choose, your JSON responses can include the version for clarity:
{
"api_version": "2.0",
"data": {
"id": "u_12345",
"name": "Alice Johnson"
}
}A Complete Well-Designed API Response
Putting it all together, here is an example of a paginated list endpoint that follows all of the best practices above:
{
"data": [
{
"id": "prod_001",
"name": "Mechanical Keyboard",
"price_cents": 12999,
"currency": "USD",
"in_stock": true,
"created_at": "2025-11-20T10:00:00Z"
},
{
"id": "prod_002",
"name": "Wireless Mouse",
"price_cents": 4999,
"currency": "USD",
"in_stock": true,
"created_at": "2025-12-01T14:30:00Z"
}
],
"pagination": {
"next_cursor": "eyJpZCI6InByb2RfMDAyIn0=",
"has_more": true,
"per_page": 2
},
"links": {
"self": "/api/v2/products?cursor=eyJpZCI6InByb2RfMDAwIn0=&per_page=2",
"next": "/api/v2/products?cursor=eyJpZCI6InByb2RfMDAyIn0=&per_page=2"
},
"meta": {
"api_version": "2.0",
"request_id": "req_xyz789",
"response_time_ms": 38
}
}Common Mistakes and How to Fix Them
Even experienced developers make JSON formatting mistakes. Here are the most frequent ones, each with an example and a fix.
1. Trailing Commas
JavaScript allows trailing commas, but JSON does not.
// INVALID JSON
{
"name": "Alice",
"age": 30,
}// VALID JSON
{
"name": "Alice",
"age": 30
}2. Single Quotes Instead of Double Quotes
JSON requires double quotes for strings and keys. Single quotes are not valid.
// INVALID JSON
{
'name': 'Alice',
'active': true
}// VALID JSON
{
"name": "Alice",
"active": true
}3. Unquoted Keys
JavaScript object literals allow unquoted keys, but JSON does not.
// INVALID JSON
{
name: "Alice",
age: 30
}// VALID JSON
{
"name": "Alice",
"age": 30
}4. Comments in JSON
JSON does not support comments of any kind. If you need comments, consider using JSONC (supported by VS Code) or JSON5, but be aware that standard parsers will reject them.
// INVALID JSON
{
// This is the user's name
"name": "Alice",
/* Multi-line
comment */
"age": 30
}// VALID JSON (use descriptive key names instead of comments)
{
"user_display_name": "Alice",
"user_age_years": 30
}5. Duplicate Keys
The JSON specification does not forbid duplicate keys, but behavior is undefined. Most parsers silently use the last value, which can mask bugs.
// PROBLEMATIC: Which "name" wins?
{
"name": "Alice",
"age": 30,
"name": "Bob"
}// CORRECT: Unique keys only
{
"name": "Bob",
"age": 30
}6. Using undefined
undefined is a JavaScript concept that does not exist in JSON. JSON.stringify will silently remove keys with undefined values.
// In JavaScript:
const obj = { name: "Alice", age: undefined };
JSON.stringify(obj);
// Result: {"name":"Alice"}
// The "age" field disappears entirely!// Use null instead when you need to indicate "no value"
const obj = { name: "Alice", age: null };
JSON.stringify(obj);
// Result: {"name":"Alice","age":null}7. Circular References
Objects that reference themselves cannot be serialized to JSON.
// This will throw: "TypeError: Converting circular structure to JSON"
const user = { name: "Alice" };
user.self = user;
JSON.stringify(user); // ERROR// Fix: Remove circular references or use a replacer function
const user = { name: "Alice", id: "u_123" };
const team = { name: "Engineering", lead_id: "u_123" };
// Reference by ID instead of by object
JSON.stringify({ user, team });8. Inconsistent Naming Within a Single Response
// BAD: Mixing camelCase and snake_case
{
"userName": "Alice",
"email_address": "[email protected]",
"phoneNumber": "+1-555-0100",
"is_active": true
}// GOOD: Consistent snake_case throughout
{
"user_name": "Alice",
"email_address": "[email protected]",
"phone_number": "+1-555-0100",
"is_active": true
}9. Storing HTML/XML in Strings Without Escaping
Embedding markup in JSON strings requires proper escaping. Unescaped angle brackets and quotes will break your JSON.
// BAD: Unescaped HTML breaks the JSON
{
"content": "<p class="intro">Hello</p>"
}// GOOD: Properly escaped
{
"content": "<p class=\"intro\">Hello</p>"
}When using JSON.stringify in JavaScript, the escaping is handled automatically. Problems usually arise when you build JSON strings by hand or with string concatenation. Always use a proper serializer.
10. Numbers with Leading Zeros
// INVALID JSON
{
"zip_code": 07001,
"port": 0080
}// VALID JSON
{
"zip_code": "07001",
"port": 80
}Leading zeros make a number literal invalid in JSON (and in many languages they indicate octal notation). If the leading zero is meaningful, store the value as a string.
Tools and Workflow
Having the right tools makes it easy to enforce formatting best practices consistently. Here are practical tools and workflows that help you write clean JSON every day.
Format and Validate with JSONEditor.net
The JSONEditor.net formatter lets you paste any JSON, instantly format it with consistent indentation, and validate it against the JSON specification. It highlights syntax errors (like those trailing commas and single quotes from the previous section) and shows you exactly where the problem is. It is the fastest way to clean up messy JSON before committing it to your project.
Compare Before and After with JSON Diff
When you refactor a JSON structure, you need to verify that the data itself has not changed, only the formatting. The JSON Diff tool lets you paste two JSON documents side by side and see exactly what has changed. This is invaluable when:
- Reformatting a configuration file and verifying no values were altered
- Comparing API responses before and after a deployment
- Reviewing changes to fixture data in pull requests
- Debugging why two seemingly identical JSON payloads produce different results
Convert Between Formats
Sometimes JSON is not the starting point. You might receive data as CSV, XML, or YAML and need to convert it to well-formatted JSON. The converter tools on JSONEditor.net handle these transformations while preserving data types and structure.
Automate Formatting in Your Workflow
Do not rely on manual formatting. Set up automation so every JSON file in your project is formatted consistently.
- Prettier: Formats JSON files automatically on save. Add
"tabWidth": 2to your Prettier config and never think about indentation again. - ESLint: Can enforce JSON formatting rules in
.jsonfiles with theeslint-plugin-jsonplugin. - Pre-commit hooks: Use
huskyandlint-stagedto format JSON files automatically before every commit. - CI checks: Add a formatting check to your CI pipeline that fails the build if any JSON file is not properly formatted.
Editor Configuration
Most modern editors support JSON-specific settings. In VS Code, add this to your workspace settings:
{
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.tabSize": 2
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.tabSize": 2
}
}Conclusion
Good JSON formatting is not about following arbitrary rules. It is about making your data predictable, your APIs pleasant to use, and your configuration files easy to maintain. The practices in this guide boil down to a few core principles:
- Be consistent. Pick a naming convention, an indentation style, and a null-handling strategy. Apply them everywhere. Consistency beats any individual preference.
- Use the right types. Booleans should be booleans, not strings. IDs that exceed safe integer limits should be strings. Currency should be in cents. Let JSON's type system do its job.
- Structure for your consumers. Group related fields, keep array item shapes consistent, and return predictable response envelopes. The people reading your JSON will thank you.
- Automate everything. Formatters, linters, pre-commit hooks, and CI checks cost minutes to set up and save hours of debugging. Never rely on manual formatting.
- Use good tools. A reliable JSON editor and formatter catches mistakes before they reach production. A diff tool verifies that refactoring did not change your data. Converters handle format transformations cleanly.
Start by auditing one JSON file in your current project. Apply these best practices, diff the result, and commit the improvement. Small, consistent changes compound into a codebase that is a pleasure to work with.