Reliable JSON handling starts before transformation: first confirm that the text is valid JSON, then check its structure, normalize known variations, and reject data that does not meet the needs of your application. This JSON validation guide provides a repeatable workflow using JSON Schema, jq, JavaScript, and Python so you can inspect API payloads, clean records, and troubleshoot unexpected fields without silently corrupting data.
Overview
JSON problems usually fall into four separate categories, and each requires a different check:
- Syntax errors: The text cannot be parsed because of a missing comma, an invalid quote, a trailing character, or another formatting problem.
- Structural errors: The JSON parses, but required properties, data types, or nested objects are missing or incorrect.
- Transformation problems: The input is valid, but fields must be renamed, filtered, flattened, grouped, or converted before use.
- Data-quality issues: Values are technically valid but unsafe or unsuitable, such as an empty identifier, an unexpected status, or a timestamp in the wrong format.
A formatter can make JSON easier to read, but formatting is not validation. A parser confirms syntax. JSON Schema checks structure and selected constraints. A transformation tool such as jq reshapes data. Application code then applies business rules, authentication decisions, and persistence logic.
A dependable workflow separates these steps:
- Preserve the original payload for debugging, while protecting secrets and personal data.
- Parse the input with a strict JSON parser.
- Validate the parsed value against a documented schema.
- Transform only the fields your application needs.
- Run application-specific checks before storing or forwarding the result.
- Record useful error context without logging sensitive payloads by default.
Checklist by scenario
When an API response will not parse
Start with the raw response rather than copying a visually formatted version from a browser. Check the HTTP status, content type, response encoding, and whether an intermediary returned HTML or plain text instead of JSON. Then pass the body through a JSON formatter or parser.
In JavaScript, parsing should be treated as an operation that can fail:
function parseJsonResponse(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : "Invalid JSON"
};
}
}
Do not “repair” malformed JSON by blindly replacing characters. A replacement may make the text parse while changing the sender’s intended value. Fix the producer or apply a clearly documented normalization step with tests.
When an API response parses but fields are unreliable
Use JSON Schema to describe the contract your code expects. This example requires an object with an identifier, a constrained status, and an array of items. The additionalProperties setting is a deliberate choice: allowing extra properties supports forward compatibility, while disallowing them can catch misspelled fields early.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "status", "items"],
"properties": {
"id": { "type": "string", "minLength": 1 },
"status": {
"type": "string",
"enum": ["pending", "complete", "failed"]
},
"items": {
"type": "array",
"items": { "type": "string" }
}
},
"additionalProperties": true
}
Keep syntax validation and schema validation separate in error messages. “Unexpected token” points to invalid JSON text; “status must be one of…” points to a contract or data-quality problem. That distinction makes API debugging and monitoring more useful.
When you need to inspect or transform JSON from the command line
jq is useful for exploring saved responses, comparing payloads, and preparing data for another command. These common filters form a compact reference:
| Goal | jq filter | Use |
|---|---|---|
| Read a property | .user.name | Retrieve a nested value. |
| Select fields | {id, status} | Create a smaller object. |
| Map an array | .items[] | .sku | Print one SKU per item. |
| Filter records | map(select(.status == "active")) | Keep matching array entries. |
| Provide a fallback | .name // "Unnamed" | Use a value when a property is null or absent. |
| Count entries | .items | length | Check an array size. |
For example, to extract active record identifiers from a file:
jq -r 'map(select(.status == "active")) | .[].id' response.json
Use --exit-status in scripts when the success or failure of a filter should affect a shell pipeline. For file operations and cleanup around these commands, follow a shell safety checklist rather than assuming every command succeeded.
When you are cleaning data in JavaScript or Python
Transform into a new object instead of mutating the original payload. This makes the boundary between external data and internal data easier to test:
function normalizeUser(input) {
return {
id: typeof input.id === "string" ? input.id.trim() : null,
name: typeof input.name === "string" ? input.name.trim() : "",
roles: Array.isArray(input.roles)
? input.roles.filter((role) => typeof role === "string")
: []
};
}
In Python, parse with the standard library and use explicit defaults:
import json
def normalize_user(text):
data = json.loads(text)
if not isinstance(data, dict):
raise ValueError("Expected a JSON object")
roles = data.get("roles", [])
if not isinstance(roles, list):
roles = []
return {
"id": data.get("id") if isinstance(data.get("id"), str) else None,
"name": data.get("name", "").strip()
if isinstance(data.get("name", ""), str) else "",
"roles": [role for role in roles if isinstance(role, str)]
}
Normalization should not hide serious contract failures. If an identifier is required, reject the record rather than converting it to null and allowing the problem to surface later in a database or downstream API.
What to double-check
- Required versus optional fields: A missing property is different from a property explicitly set to
null. Decide which states your application accepts. - Types: JSON distinguishes strings, numbers, booleans, arrays, objects, and null. A numeric-looking string such as
"42"is not the same as the number42. - Numbers: Check how your language handles large integers, decimal precision, and non-finite values. Do not assume every producer and consumer represent numbers identically.
- Dates: JSON has no native date type. Define an accepted string format, preferably with a documented timezone policy, and validate it separately from basic string type checks.
- Unknown properties: Decide whether extra fields should be ignored, preserved, warned about, or rejected. The right choice depends on whether forward compatibility or strict contracts matter more.
- Arrays: Check whether an empty array is valid, whether item order matters, and whether duplicates are allowed.
- Security boundaries: Never treat parsed JSON as trusted merely because it is valid. Validate authorization-related fields on the server and avoid logging tokens, credentials, or complete sensitive payloads.
- Output shape: After transformation, validate the result again if it will be sent to another service or written to a strict data store.
For HTTP troubleshooting, inspect the request and response in browser developer tools, then compare the actual payload with the documented contract. If failures involve retries, timeouts, or partial responses, pair JSON checks with a dedicated API error-handling workflow.
Common mistakes
Confusing formatting with validation. A JSON formatter improves readability but cannot confirm that a payload has the required business fields.
Using truthiness for required values. Code such as if (!value) may reject valid values such as 0 or false. Check the expected type and presence explicitly.
Assuming missing and null mean the same thing. Use a deliberate rule for each field. A missing property may indicate an older producer, while null may be an intentional statement that no value exists.
Dropping unknown fields without deciding why. Filtering can protect internal models from accidental data leakage, but it can also remove information needed for future features. Document the boundary.
Logging entire failed payloads. Debugging is important, but raw JSON may contain access tokens, email addresses, or other sensitive values. Prefer request identifiers, field-level errors, and redacted samples.
Relying on one sample response. Test empty arrays, missing optional fields, nulls, unexpected enum values, duplicate records, large values, and malformed input. A compact fixture set is often more useful than a single large example.
Transforming before validating. Early coercion can hide a producer defect. Parse first, validate the contract, then normalize values according to an explicit rule.
When to revisit
Revisit this checklist whenever an API version changes, a new data producer is introduced, a JSON Schema draft or validation library is upgraded, or a transformation moves from an interactive command into automation. It is also worth reviewing before seasonal planning cycles or scheduled migrations, when payload volume and edge cases may differ from routine traffic.
Keep the schema, sample payloads, jq filters, and normalization tests close to the code that consumes them. Add a regression fixture whenever a production payload exposes a new variation. If a command-line workflow becomes part of a deployment or scheduled job, review its exit codes, temporary files, quoting, and cleanup using a shell reliability checklist.
Before shipping a JSON integration, complete this practical sequence:
- Save a redacted valid payload and representative edge cases.
- Confirm that parsing failures are distinguishable from schema failures.
- Write or update the JSON Schema for required fields and types.
- Test transformations with missing, null, empty, and unexpected values.
- Validate the transformed output if another system will consume it.
- Review logs to ensure errors are actionable without exposing sensitive data.
- Record the producer version, schema expectation, and last review date.
This process turns JSON handling from ad hoc cleanup into a maintainable developer tool workflow—one you can repeat whenever the input, contract, or surrounding tools change.