How to Format JSON: Complete Guide to JSON Formatting, Validation & Best Practices

Everything you need to know about formatting, validating, and working with JSON data in modern development.

Advertisement

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the de facto standard for data exchange on the web. Created by Douglas Crockford in the early 2000s, JSON is easy for humans to read and write, and easy for machines to parse and generate. It is based on a subset of JavaScript but is language-independent, with parsers available for virtually every programming language.

JSON supports six data types: strings (in double quotes), numbers, booleans (true/false), null, arrays (ordered lists), and objects (key-value pairs). This simplicity is one of its greatest strengths — unlike XML, JSON has minimal syntax overhead, making it ideal for APIs, configuration files, and data storage.

Today, JSON is used everywhere: REST APIs, NoSQL databases like MongoDB, configuration files for tools like package.json and tsconfig.json, and even as a data format for machine learning datasets. Understanding how to properly format and validate JSON is an essential skill for every developer.

Why Format JSON?

Raw JSON data from APIs or databases is often minified — compressed into a single line with no whitespace. While this is efficient for data transfer (reducing payload size by 10-30%), it is nearly impossible to read. JSON formatting adds proper indentation and line breaks, transforming an unreadable blob into a structured, scannable document.

Formatted JSON is essential for:

  • Debugging API responses — Quickly identify missing fields, incorrect types, or unexpected values
  • Code reviews — Reviewers can easily scan configuration changes in formatted JSON
  • Documentation — Formatted JSON examples in docs are much more readable
  • Configuration management — Formatted config files are easier to maintain and version control
  • Data analysis — Understanding the structure of complex nested JSON objects

How to Format JSON in JavaScript

JavaScript provides built-in JSON formatting through JSON.stringify(). The third parameter controls indentation:

// Format with 2-space indentation
const data = { name: "John", age: 30, hobbies: ["coding", "reading"] };
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
// Output:
// {
//   "name": "John",
//   "age": 30,
//   "hobbies": [
//     "coding",
//     "reading"
//   ]
// }

// Format with tab indentation
const tabFormatted = JSON.stringify(data, null, "	");

// Minify (remove all whitespace)
const minified = JSON.stringify(data);

The second parameter of JSON.stringify() is a replacer function or array that lets you filter or transform values during serialization. This is useful for removing sensitive data or converting types:

// Remove sensitive fields
const user = { name: "John", password: "secret", email: "john@example.com" };
const safe = JSON.stringify(user, ["name", "email"], 2);
// Only includes name and email

// Custom replacer function
const formatted = JSON.stringify(data, (key, value) => {
  if (typeof value === "string") return value.toUpperCase();
  return value;
}, 2);

How to Validate JSON

JSON validation ensures your data conforms to the JSON specification. The simplest way to validate JSON in JavaScript is with a try-catch block:

function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

// Usage
console.log(isValidJSON('{"name": "John"}')); // true
console.log(isValidJSON("{'name': 'John'}")); // false (single quotes)
console.log(isValidJSON("{name: 'John'}")); // false (unquoted key)

For more advanced validation, consider JSON Schema — a vocabulary that allows you to annotate and validate JSON documents. Libraries like Ajv (Another JSON Schema Validator) provide fast, standards-compliant validation:

import Ajv from "ajv";
const ajv = new Ajv();

const schema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "integer", minimum: 0 },
    email: { type: "string", format: "email" }
  },
  required: ["name", "email"]
};

const validate = ajv.compile(schema);
const valid = validate({ name: "John", age: 30, email: "john@example.com" });
console.log(valid); // true

Common JSON Errors and How to Fix Them

Here are the most frequent JSON errors developers encounter:

1. Trailing Commas

// ❌ Invalid - trailing comma
{ "name": "John", "age": 30, }

// ✅ Valid
{ "name": "John", "age": 30 }

2. Single Quotes

// ❌ Invalid - single quotes
{ 'name': 'John' }

// ✅ Valid - double quotes only
{ "name": "John" }

3. Unquoted Keys

// ❌ Invalid - unquoted keys
{ name: "John" }

// ✅ Valid
{ "name": "John" }

4. Comments

// ❌ Invalid - comments not allowed
{
  "name": "John", // user name
  "age": 30 /* years */
}

// ✅ Valid - no comments
{ "name": "John", "age": 30 }

5. Special Values

// ❌ Invalid - undefined, NaN, Infinity not allowed
{ "value": undefined, "count": NaN, "max": Infinity }

// ✅ Valid - use null instead
{ "value": null, "count": 0, "max": 999999 }

JSON Formatting Best Practices

  • Use consistent indentation — Pick 2 spaces, 4 spaces, or tabs and stick with it across your project. Configure your editor and linter to enforce this.
  • Use meaningful key names — Choose descriptive, camelCase key names like firstName instead of fn.
  • Keep nesting shallow — Deeply nested JSON (5+ levels) is hard to read and work with. Consider flattening your data structure.
  • Validate before parsing — Always validate JSON from external sources before parsing to prevent errors and potential security issues.
  • Use JSON Schema for APIs — Define schemas for your API request/response bodies to ensure data consistency.
  • Minify for production — Use minified JSON for API responses and data transfer to reduce bandwidth usage.
  • Format for version control — Store formatted JSON in Git repositories so diffs are meaningful and reviewable.

JSON Formatting Tools

There are many tools available for formatting JSON:

  • Our JSON Formatter — Free online tool with syntax highlighting, tree view, and validation
  • VS Code — Built-in JSON formatting with Shift+Alt+F (or configure format on save)
  • jq — Command-line JSON processor: echo '{"a":1}' | jq .
  • Prettier — Code formatter that handles JSON along with JavaScript, TypeScript, CSS, and more
  • Pythonpython -m json.tool file.json

Try Our JSON Formatter

Format, validate, and beautify your JSON data instantly with our free online tool. Features syntax highlighting, tree view, and configurable indentation.

Open JSON Formatter →
Advertisement