You have a blob of JSON and something's wrong with it. Maybe it came from an API response mashed into one long line. Maybe a colleague sent it over Slack and the formatting got mangled. Maybe you're staring at a config file that was working yesterday and now your app won't start, throwing a cryptic "Unexpected token" error somewhere.
JSON looks simple - and it is, structurally. But even a single misplaced comma or wrong quote character breaks the whole thing. This guide covers how to format JSON so you can actually read it, validate it to find exactly what's wrong, and fix the most common problems. We'll go from the quickest approach (paste it into a tool) through programmatic solutions you can build into your workflow.
The Quick Way: Use a Browser Tool
When you just need to format or validate a chunk of JSON right now, a browser-based tool is the fastest option. No installation, no setup, no context switching to a terminal.
The JSON Formatter & Validator tool handles both at once. Paste your JSON, and it immediately pretty-prints it with proper indentation and highlights any syntax errors with the exact location and description. It runs entirely in your browser - nothing gets uploaded to a server.
Quick steps:
- Go to articleformatter.com/json-formatter
- Paste your JSON into the input area
- The tool formats and validates automatically
- If there are errors, you'll see exactly where they are
- Copy the formatted output
This works well for quick checks - debugging API responses, cleaning up config files, or verifying that the JSON you just wrote is actually valid before committing it.
JavaScript: Parse, Format, and Validate
If you're working in JavaScript already - building a web app, writing a Node.js script, or automating something - the language has solid built-in JSON handling.
Pretty-printing with JSON.stringify
The third argument to JSON.stringify controls indentation. Most people only use the first argument and forget about this one:
const data = {"name":"Alice","age":30,"skills":["JavaScript","Python"]};
// Pretty-print with 2-space indent
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
// {
// "name": "Alice",
// "age": 30,
// "skills": [
// "JavaScript",
// "Python"
// ]
// }
The second argument is a replacer function or array - useful for filtering out specific keys. Pass null to include everything. The third argument can be a number (spaces) or a string (like "\t" for tabs).
Validating with try/catch
JSON.parse throws a SyntaxError on invalid input. Wrap it in a try/catch to get the error details:
function validateJson(str) {
try {
const parsed = JSON.parse(str);
return { valid: true, data: parsed };
} catch (err) {
return { valid: false, error: err.message };
}
}
// Usage
const result = validateJson('{"name": "Alice", }');
// { valid: false, error: "Expected double-quoted property name in JSON at position 19" }
The error message from JSON.parse usually tells you the character position where it failed. In V8 (Node.js, Chrome), the messages are pretty descriptive. Safari's tend to be more terse.
Minifying JSON
Going the other direction - removing all whitespace to make JSON as small as possible:
const minified = JSON.stringify(JSON.parse(prettyJson));
// One line, no extra spaces This is useful before sending JSON over the network or storing it in a database where the whitespace just wastes space. Parse first, then stringify without the indent argument.
Python: json Module and Beyond
Python's standard library includes a solid json module. It handles formatting, validation, and most common operations without installing anything extra.
Pretty-printing
import json
data = '{"name":"Alice","age":30,"skills":["JavaScript","Python"]}'
# Parse and pretty-print
parsed = json.loads(data)
formatted = json.dumps(parsed, indent=2, sort_keys=True)
print(formatted)
The sort_keys=True option alphabetizes the keys, which makes it easier to compare two JSON objects visually. You can also use ensure_ascii=False to keep Unicode characters readable instead of escaping them to \uXXXX.
Validation with error details
import json
def validate_json(text):
try:
data = json.loads(text)
return True, data
except json.JSONDecodeError as e:
return False, f"Line {e.lineno}, Column {e.colno}: {e.msg}"
valid, result = validate_json('{"name": "Alice", }')
# (False, 'Line 1, Column 20: Expecting property name enclosed in double quotes')
Python's JSONDecodeError gives you line number, column number, and a human-readable message. This is more precise than what most JavaScript engines provide.
Working with JSON files
import json
# Read and format a JSON file
with open('data.json', 'r') as f:
data = json.load(f)
# Write back formatted
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)
f.write('\n') # Trailing newline, keeps git happy That trailing newline matters. Most text editors and linters expect files to end with a newline. Without it, git diffs show a "No newline at end of file" warning that clutters your commits.
Command Line: jq, python -m json.tool, and More
The command line is where JSON formatting gets really efficient, especially when you're already working in a terminal or need to process JSON in scripts and pipelines.
python -m json.tool (built-in)
This is available anywhere Python is installed - no extra packages needed:
# Format a JSON file
python3 -m json.tool data.json
# Format JSON from a pipe
curl -s https://api.example.com/data | python3 -m json.tool
# Validate only (exit code 1 if invalid)
python3 -m json.tool data.json > /dev/null
If the JSON is invalid, you get a clear error message with the position. If it's valid, you get pretty-printed output. Redirect to /dev/null and check the exit code when you just want a yes/no validation without output.
jq (the Swiss army knife)
If you work with JSON regularly, jq is worth installing. It formats, queries, filters, and transforms JSON from the command line:
# Pretty-print
cat data.json | jq .
# Extract a specific field
cat data.json | jq '.name'
# Format with sorted keys
cat data.json | jq -S .
# Minify (compact output)
cat data.json | jq -c .
# Validate without output
jq empty data.json
The jq empty command is a clean validation check. It outputs nothing on valid JSON and prints the error on invalid input. And jq -S . sorts keys, which is great for diffing two JSON files with consistent key ordering.
Comparing two JSON files
When you need to find differences between two JSON files, format them consistently first. Otherwise, whitespace and key order differences will swamp the real changes:
# Sort keys and diff
diff <(jq -S . file1.json) <(jq -S . file2.json)
# Or use our text diff tool for a visual comparison You can also paste both versions into a Text Diff Checker for a visual side-by-side comparison with highlighted changes.
Common JSON Errors and How to Fix Them
Most JSON errors fall into a handful of categories. Here are the ones you'll run into over and over, with the exact fix for each.
1. Trailing commas
This is probably the single most common JSON error:
// INVALID - trailing comma after "Python"
{
"skills": ["JavaScript", "Python",]
}
// VALID
{
"skills": ["JavaScript", "Python"]
} JavaScript and Python both allow trailing commas in their own syntax, which is why this trips people up. JSON does not. Remove the comma after the last item in any array or object.
2. Single quotes instead of double quotes
// INVALID - single quotes
{'name': 'Alice'}
// VALID - double quotes only
{"name": "Alice"}
JSON requires double quotes around all strings and property names. No exceptions. This is the one that bites Python developers most often, since Python dictionaries print with single quotes by default. Always use json.dumps() to serialize, not str().
3. Unquoted property names
// INVALID - unquoted keys
{name: "Alice", age: 30}
// VALID
{"name": "Alice", "age": 30} JavaScript object literals let you skip the quotes on keys. JSON doesn't. Every property name must be a double-quoted string. This is a common problem when someone hand-types JSON instead of generating it from code.
4. Comments
// INVALID - JSON does not support comments
{
"port": 3000, // development port
"host": "localhost"
}
// VALID - remove the comment
{
"port": 3000,
"host": "localhost"
} This is a deliberate design choice. Douglas Crockford left comments out of the JSON spec because he saw them being used to hold parsing directives, which defeated the purpose of a simple data format. If you need comments in config files, consider JSONC (JSON with Comments, used by VS Code), YAML, or TOML instead.
5. Wrong data types
// INVALID
{
"active": True, // Python-style boolean
"count": undefined, // JavaScript undefined
"data": NaN // Not a valid JSON value
}
// VALID
{
"active": true,
"count": null,
"data": 0
}
JSON booleans are lowercase: true and false, not True/False. The only "empty" value is null (lowercase). There's no undefined, no NaN, no Infinity.
JSON Schema: Structural Validation
Basic validation tells you whether something is valid JSON. Schema validation goes further - it tells you whether the JSON matches a specific shape. Does it have the right fields? Are the values the right types? Are required fields present?
What JSON Schema looks like
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["name", "email"],
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0
}
}
}
This schema says: the data must be an object with a required name (non-empty string), a required email (valid email format), and an optional age (non-negative integer).
Validation in JavaScript (Ajv)
import Ajv from 'ajv';
const ajv = new Ajv();
const validate = ajv.compile(schema);
const data = { name: "Alice", email: "[email protected]" };
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
// Detailed array of what failed and where
} Validation in Python (jsonschema)
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"required": ["name", "email"],
"properties": {
"name": {"type": "string"},
"email": {"type": "string", "format": "email"}
}
}
try:
validate(instance={"name": "Alice"}, schema=schema)
except ValidationError as e:
print(e.message)
# "'email' is a required property" Schema validation is especially useful for APIs where you're receiving JSON from external sources and need to verify it matches what your code expects before processing it.
Editor Integration
Most code editors can format JSON without leaving the editor. This is probably where you'll format JSON most often once you set it up.
VS Code. Open a .json file and press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac) to auto-format. VS Code validates JSON files in real-time and underlines errors with red squiggly lines. It also supports JSONC for config files like settings.json.
Vim/Neovim. Select the JSON and run :%!python3 -m json.tool to format the entire file through Python's formatter. For validation, the error output tells you exactly where the problem is.
JetBrains IDEs. (WebStorm, PyCharm, IntelliJ) Press Ctrl+Alt+L to reformat. These IDEs also validate JSON against schemas automatically when you reference a $schema URL in the file.
Sublime Text. Install the Pretty JSON package. Then use Ctrl+Alt+J to format, Ctrl+Alt+M to minify.
Method Comparison
| Method | Format | Validate | Schema | Best For |
|---|---|---|---|---|
| Browser tool | Yes | Yes | No | Quick one-off tasks |
| JSON.stringify/parse | Yes | Yes | With Ajv | JavaScript apps |
| Python json module | Yes | Yes | With jsonschema | Python scripts, data work |
| python -m json.tool | Yes | Yes | No | Quick CLI formatting |
| jq | Yes | Yes | No | CLI power users, pipelines |
| VS Code / editor | Yes | Yes | Yes | Daily editing workflow |
Real-World Use Cases
Here are the scenarios where you'll reach for JSON formatting and validation tools most often.
Debugging API responses. An endpoint returns a single long line of JSON. You can't read it. Paste it into the JSON Formatter or pipe it through jq . to see the structure. Half the time, seeing the data formatted is enough to spot what's wrong.
Config file troubleshooting. Your app crashes on startup with a JSON parse error. The config file is 200 lines long. Run it through a validator to get the exact line and column of the error. Usually it's a trailing comma you added when you appended a new setting.
API request building. You're constructing a POST body and need to make sure it's valid before sending it. Format it, validate it, then minify it for the request. The Article Formatter can clean up the whitespace and special characters that sometimes sneak in from copying between apps.
Comparing JSON payloads. Two API responses should be identical but something changed. Format both with sorted keys, then run a diff. Or paste both into the Text Diff Checker to see exactly which fields changed.
Data cleanup and migration. You exported data from one system as JSON and need to import it into another. But the export has inconsistent formatting, extra whitespace, or slightly wrong structure. Parse it, clean it up, validate against the target schema, and format it for the import.
Tips for Working with Large JSON Files
Small JSON blobs are easy. But when you're dealing with megabytes of JSON - database exports, API dumps, log aggregations - things get trickier.
- Don't open huge JSON in a browser tool. Browser-based formatters load everything into memory. A 50MB JSON file will freeze the tab. Use command-line tools instead.
- Stream with jq.
jqstreams JSON by default, so it can handle large files without loading everything into memory at once. - Use
--sort-keysfor consistent output. When comparing large files, sorted keys prevent false diffs from key ordering changes. - Validate before parsing. If you're loading a huge file into an application, validate it first. A parse error at byte 49,999,999 of a 50MB file after waiting 30 seconds is frustrating.
- Consider JSON Lines (JSONL) for large datasets. Instead of one massive array, put each record on its own line as a separate JSON object. This lets you process records one at a time and makes the file appendable.
Frequently Asked Questions
What is the fastest way to format JSON?
jq . file.json or python3 -m json.tool file.json are the fastest CLI options.
What are the most common JSON validation errors?
True/False instead of true/false.
How do I validate JSON from the command line?
python3 -m json.tool file.json (built-in, no install needed) or jq empty file.json (needs jq installed). Both print the error location on invalid JSON and succeed silently on valid JSON. Check the exit code in scripts: 0 means valid, 1 means invalid.
What is the difference between JSON validation and JSON Schema validation?
Related Tools
JSON Formatter & Validator
Format, validate, and minify JSON right in your browser. Syntax highlighting and error detection.
Text Diff Checker
Compare two JSON payloads side by side and see exactly what changed.
Article Formatter
Clean up text formatting, fix encoding issues, and prepare content for publishing.
CSV to Table Converter
Convert between data formats - turn CSV data into formatted tables.