How to Format and Validate JSON Before Sending an API Request
A missing comma. A trailing bracket. A property name without quotes. Any one of these tiny mistakes turns a perfectly constructed API request into a 400 Bad Request error that can take longer to debug than the feature took to build. JSON is unforgiving โ a single character out of place makes the entire document invalid.
Validate JSON instantly: Paste any JSON to see exact error locations and diagnostics โ no signup required.
Open JSON Validator โTable of Contents
The Most Common JSON Syntax Errors
Trailing commas
// INVALID โ trailing comma after last property
{ "name": "Alice", "email": "[email protected]", }
// VALID
{ "name": "Alice", "email": "[email protected]" }
JavaScript and TypeScript allow trailing commas but JSON does not. This is the most common source of broken API requests in codebases that copy objects from JS files.
Single quotes
// INVALID โ single quotes
{'name': 'Alice'}
// VALID โ double quotes required
{"name": "Alice"}
Unquoted property names
// INVALID โ bare property names (valid JS object literal, not JSON)
{name: "Alice", age: 30}
// VALID
{"name": "Alice", "age": 30}
Comments
JSON has no support for comments. // and /* */ will cause a parse error in any strict JSON parser. If you need comments in config files, use JSONC or YAML instead.
Wrong keyword casing
// INVALID โ keywords are case-sensitive
{"active": True, "data": NULL}
// VALID โ must be lowercase
{"active": true, "data": null}
Unescaped special characters in strings
// INVALID โ raw newline inside string
{"message": "Hello
World"}
// VALID โ escaped newline
{"message": "Hello
World"}
Formatting JSON for Readability
Minified JSON is fine for transmission but terrible for review. Always format JSON when debugging API responses. The standard is two-space indentation with each key-value pair on its own line.
Format JSON instantly: Our JSON Formatter handles minified, messy, or deeply nested JSON and outputs clean indented results.
Open JSON Formatter โValidating JSON in Code
// JavaScript
try {
const data = JSON.parse(jsonString);
} catch (e) {
console.error('Invalid JSON:', e.message);
}
# Python
import json
try:
data = json.loads(json_string)
except json.JSONDecodeError as e:
print(f'Line {e.lineno}, col {e.colno}: {e.msg}')
# Go
var data interface{}
if err := json.Unmarshal([]byte(s), &data); err != nil {
log.Printf("Invalid JSON: %v", err)
}
Building Validation Into Your Workflow
- Use a linter in your editor. VS Code's built-in JSON support flags errors as you type.
- Validate in pre-commit hooks.
python -m json.tool file.jsoncatches invalid JSON before it's committed. - Test API requests with Postman or Insomnia before wiring into application code.
- Log the raw request body in development so you can inspect exactly what was sent.
- Use JSON Schema validation (ajv, jsonschema) to validate not just syntax but structure and types.
JSON Validation in CI/CD Pipelines
Catching invalid JSON before it reaches an API endpoint saves debugging time and prevents cascading failures. In a CI/CD pipeline, you can add a validation step that checks all JSON configuration files, request fixtures, and mock data for syntax errors. Tools like jq on the command line will fail with an exit code on invalid JSON, making it easy to integrate into shell-based pipelines: cat config.json | jq . > /dev/null will fail if the JSON is malformed.
For API request validation at runtime, always validate incoming JSON before processing it. In Express.js, the built-in express.json() middleware will reject requests with invalid JSON bodies and return a 400 status. In Python Flask, request.get_json(force=True, silent=True) returns None on invalid JSON rather than raising an exception, so always check for None before proceeding.
Schema Validation Beyond Syntax
Syntax validation only checks that JSON is structurally correct โ it doesn't verify that the data makes sense for your application. A request body of {"name": 42, "email": true} is valid JSON but useless for a user registration endpoint. Schema validation tools like JSON Schema, Zod (TypeScript), and Pydantic (Python) let you define expected shapes and types, catching semantic errors before they reach your business logic.
JSON Schema is the most portable approach since it's language-agnostic โ define the schema once and validate in any language. For TypeScript projects, Zod has become the de facto choice because it infers TypeScript types from the schema definition, eliminating the duplication between runtime validation and compile-time types. Pydantic serves the same role in the Python ecosystem, with the added benefit of automatic serialization and deserialization.
Pretty-Printing for Debugging vs Production
Formatted JSON is essential for debugging โ a 500-character single-line blob is unreadable, but the same data indented with 2-space tabs reveals its structure immediately. Most languages let you control this: JavaScript's JSON.stringify(obj, null, 2) produces indented output, while Python's json.dumps(obj, indent=2) does the same. In production, always use compact JSON (no whitespace) for API responses, as the indentation characters add 20-40% to payload size on typical nested objects.
For complex nested structures, consider using a tool that supports collapsible tree views rather than raw text. The JSON Formatter in your browser renders JSON as an interactive tree where you can expand and collapse nodes, making it far easier to navigate deeply nested API responses than scrolling through formatted text.
