Validate JSON Before API Requests
A quick validation pass before sending an API request can separate JSON syntax problems from authentication, schema, and backend errors.
Why Validate Before Sending
When an API request fails, the error may point to authentication, permissions, schema validation, or malformed JSON. Validating the JSON body first removes one entire class of failures before the request reaches the server — and makes copied curl commands, Postman bodies, webhook samples, and integration tests easier to review. Paste a payload into the strict JSON validator to confirm it conforms to RFC 8259 before sending.
Syntax Checks to Run
A strict JSON validation pass should confirm that the body parses and matches what you intended to send. The recurring traps:
| Check | What you're catching |
|---|---|
| Every string and object key uses double quotes | Single-quoted output from a JavaScript / Python repr — see fix single quotes |
| No comments, no trailing commas | Pasted from JSONC, JSON5, or hand-edited config — see fix trailing commas |
Booleans are true / false (lowercase) |
Python True / False snuck through a stringification |
Missing values are null or omitted, never undefined |
JavaScript undefined is not a JSON value; it disappears on JSON.stringify |
| Top-level value matches the endpoint expectation | Some APIs want an object, some want an array, some want a primitive |
| Numeric IDs match the schema's expected type | A 16-digit ID sent as a number loses precision in JS clients — quote it if the server expects a string |
Headers Still Matter
A valid JSON body can still fail if the request doesn't declare the right content type:
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ userId: 42, active: true }),
});
For most JSON APIs, send Content-Type: application/json so the server knows to parse the body as JSON. Add Accept: application/json so the server's response uses the same format. Without Content-Type, many servers treat the body as text/plain or application/x-www-form-urlencoded and the parse fails with a misleading error.
Broken Request Body
{
userId: 42,
active: True,
tags: ['beta',],
}
Three problems in five lines: unquoted userId key, Python-style True, single-quoted 'beta' value, trailing comma after 'beta'.
Fixed Request Body
{
"userId": 42,
"active": true,
"tags": ["beta"]
}
Run the broken version through JSON Fix (auto-repair handles all four issues in one pass), then re-validate.
After Syntax Validation
Syntax validation only proves the document is parseable. For production requests, also check the shape: required fields, unknown fields, value types, array lengths, enum values, date strings, and whether numeric identifiers should be numbers or strings.
import Ajv from 'ajv';
const ajv = new Ajv();
const validate = ajv.compile({
type: 'object',
required: ['userId', 'active'],
properties: {
userId: { type: 'integer' },
active: { type: 'boolean' },
tags: { type: 'array', items: { type: 'string' } },
},
additionalProperties: false,
});
const res = await fetch(url, { method: 'POST', headers, body });
const data = await res.json();
if (!validate(data)) {
throw new Error('Schema mismatch: ' + ajv.errorsText(validate.errors));
}
Compile the schema once at module load, then guard every call. This surfaces upstream contract breaks at the boundary, not five layers deep in the application code. JSON Schema is the underlying spec; Ajv is the most-used JS implementation, with peers in Zod (TS-first) and Python's jsonschema library.
Debugging Tip
If a server still rejects valid JSON, compare the formatted request body against a known-good example with the JSON Diff tool — semantic diffing finds real value changes while ignoring object key order, which is especially useful when payloads are generated by different tools (a curl command vs a Postman export vs an SDK call).
See also
The hub explains why the validate-and-repair workflow on this site runs entirely in your browser — no upload endpoint, no server-side logs.
Sources
- RFC 8259 — the JSON Data Interchange Format (the "valid JSON" reference)
- JSON Schema — the spec for declaring required fields, types, and constraints
- Ajv — the most-used JSON Schema validator for JavaScript / TypeScript
- MDN —
fetch(the standard request API, including howContent-Typeis read)
Last reviewed June 2026.
JSON repair guides
Topic hubs
- JSON Parse Errors: Read the Message, Jump to the Fix
- Fix Invalid JSON: From 'What's Wrong' to a Clean File
- JSON Formatter, Validator, Viewer: Pick the Right Tool
- Repair LLM JSON Output: Handling Almost-JSON from AI
- Privacy: JSON Tools That Don't Leave Your Browser
- JSON Interop: YAML, CSV, XML, JWT, Schema
Specific guides
- How to Decode Base64 Strings (and JWT Payloads)
- URL Encoding: Percent-Encode Query Parameters and Paths
- Convert YAML to JSON (and Avoid Indentation Errors)
- Convert JSON to CSV: Flatten an Array of Objects
- Convert JSON to XML: Root Elements, Attributes, and Arrays
- Escape JSON as a String Literal (and Decode Double-Encoded JSON)
- Fix Trailing Comma in JSON
- Fix Single Quotes in JSON
- Fix Unquoted Keys in JSON
- Repair LLM JSON Output
- Fix JSON Parse Error: Expected Property Name
- JSON vs JS Object Literal: The Key Differences
- JSON Formatter vs JSON Repair
- Fix JSON Unexpected Token Errors
- JSON to JavaScript Object Converter