DEV Community

ze he
ze he

Posted on • Originally published at aiforeverthing.com

JSON Formatting 101: Beautify, Validate, and Minify JSON Like a Pro

JSON Formatting 101: Beautify, Validate, and Minify JSON Like a Pro

Every developer has pasted a wall of minified JSON into a terminal and wished it was readable. This guide covers everything about JSON formatting — why it matters, common errors, and how to automate it.

TL;DR: Use aiforeverthing.com/json-formatter.html to instantly format, validate, or minify JSON in your browser (free, no signup, 100% private).


What Is JSON Formatting?

JSON formatting (also called "pretty printing" or "beautifying") converts compact JSON:

{"user":{"id":"123","name":"Alice","role":"admin"}}
Enter fullscreen mode Exit fullscreen mode

Into human-readable form:

{
  "user": {
    "id": "123",
    "name": "Alice",
    "role": "admin"
  }
}
Enter fullscreen mode Exit fullscreen mode

The data is identical — only whitespace and indentation are added.


The 3 JSON Operations Every Dev Needs

1. Format / Beautify

Adds indentation and line breaks. Use this when:

  • Reading API responses
  • Debugging webhook payloads
  • Reviewing config files

In JavaScript:

const pretty = JSON.stringify(obj, null, 2); // 2-space indent
Enter fullscreen mode Exit fullscreen mode

In Python:

import json
pretty = json.dumps(obj, indent=2)
Enter fullscreen mode Exit fullscreen mode

In the terminal:

echo '{}' | python3 -m json.tool
# or
cat data.json | jq .
Enter fullscreen mode Exit fullscreen mode

2. Validate

JSON has strict rules that trip up developers coming from JavaScript:

What fails Why Fix
{name: "Alice"} Keys must be quoted {"name": "Alice"}
{'name': 'Alice'} Single quotes not allowed Use double quotes
{"a": 1,} Trailing commas Remove the comma
{"a": undefined} undefined not a JSON type Use null
{"fn": function(){}} Functions not serializable Remove or transform
// Safe JSON parsing pattern
function safeParseJSON(str) {
  try {
    return { data: JSON.parse(str), error: null };
  } catch (e) {
    return { data: null, error: e.message };
  }
}

const { data, error } = safeParseJSON(rawInput);
if (error) console.error("Invalid JSON:", error);
Enter fullscreen mode Exit fullscreen mode

3. Minify

Strips all whitespace for smaller payloads:

const minified = JSON.stringify(obj); // No indent = compact
Enter fullscreen mode Exit fullscreen mode

When to minify:

  • API responses going over the wire
  • Storing JSON in databases or localStorage
  • Embedding JSON in HTML <script> tags
  • CI/CD pipeline config comparisons

Advanced: Sort Keys for Cleaner Git Diffs

Sorting JSON keys alphabetically makes diffs much cleaner:

function sortJSON(obj) {
  if (Array.isArray(obj)) return obj.map(sortJSON);
  if (obj !== null && typeof obj === 'object') {
    return Object.keys(obj).sort().reduce((acc, key) => {
      acc[key] = sortJSON(obj[key]);
      return acc;
    }, {});
  }
  return obj;
}

const sorted = JSON.stringify(sortJSON(bigObj), null, 2);
Enter fullscreen mode Exit fullscreen mode

This is invaluable in code review — without sorted keys, two semantically-identical JSON objects produce noisy diffs.


Format JSON via API (For Automation)

The DevKits REST API lets you format JSON programmatically — useful for CI pipelines, scripts, or apps:

curl -X POST https://api.aiforeverthing.com/api/json/format \
  -H "Content-Type: application/json" \
  -d '{"json": "{\"name\":\"Alice\",\"age\":30}", "indent": 2}'
Enter fullscreen mode Exit fullscreen mode

Free tier: 100 requests/day. No signup required.


Debugging JSON in Real Projects

Format curl API responses

curl -s https://api.example.com/users | jq .
# or without jq:
curl -s https://api.example.com/users | python3 -m json.tool
Enter fullscreen mode Exit fullscreen mode

Node.js circular reference safe logging

const seen = new Set();
console.log(JSON.stringify(obj, (key, value) => {
  if (typeof value === 'object' && value !== null) {
    if (seen.has(value)) return '[Circular]';
    seen.add(value);
  }
  return value;
}, 2));
Enter fullscreen mode Exit fullscreen mode

Pre-commit hook to validate JSON files

#!/bin/sh
# .git/hooks/pre-commit
for file in $(git diff --cached --name-only | grep '\.json$'); do
  python3 -m json.tool "$file" > /dev/null 2>&1 || {
    echo "Invalid JSON: $file"
    exit 1
  }
done
Enter fullscreen mode Exit fullscreen mode

Quick Reference

Tool Best For
DevKits JSON Formatter Browser-based, instant, syntax highlighting
jq Command-line, powerful filtering
python3 -m json.tool Terminal, built-in, no deps
DevKits API Programmatic formatting in apps/CI
VS Code Editor with auto-format on save

Summary

  • Format JSON to make it readable (debugging, reviews)
  • Validate to catch syntax errors before runtime
  • Minify to reduce payload size in production
  • Sort keys for cleaner git diffs
  • Use the free online formatter for quick one-off tasks
  • Use the DevKits API for automation

Happy formatting!

Top comments (0)