
How to validate JSON before using an API response
A valid JSON document is syntactically parseable, but syntactic validity is only the first step in checking an API payload.
What validation actually checks
When you validate JSON, you are really running several different checks at once, and it helps to keep them separate. The first check is syntax: does the document follow the JSON grammar, with double-quoted strings, commas between items, and matching brackets and braces? A parser answers this question with a yes or no. If the answer is no, nothing else about the payload can be trusted yet, because the document cannot even be read reliably.
The second check is structure: does the parsed result have the shape your code expects? An API might return an object when you expected an array, or nest the data one level deeper than your code assumes. A document can be perfectly valid JSON and still break your application if the structure is wrong. That is why checking the top-level type is worth doing first, before you read any single field.
The third check is content: are the fields present, and do they have the types and value ranges you need? A missing user id, a price stored as a string instead of a number, or a status field with an unexpected value can all pass a syntax check and still cause wrong behaviour. Good validation checks names, types, required fields, and reasonable ranges, not just whether the document parses.
A practical step-by-step check
A repeatable routine makes validation faster and less error-prone. Start with the raw response exactly as it arrived, before any code has transformed it. Confirm the response is really JSON and not an HTML error page, a plain-text message, or an empty body that your code is about to treat as data. Many confusing failures turn out to be a login page or a rate-limit notice being parsed as if it were JSON.
- Paste or load the raw response into a JSON formatter and validator and confirm it parses without errors.
- Check the top-level type. If you expect an object, confirm you got an object; if you expect a list, confirm you got a list.
- Check every required field by name, and confirm each one has the expected type, such as string, number, boolean, array, or object.
- Check value ranges and formats that matter: numbers within plausible bounds, dates in the expected format, and status values drawn from the documented set.
- Check nested objects and arrays the same way, one level at a time, rather than assuming the whole payload is fine because the top level looks right.
- Test with more than one real response, including an empty result, a single-item result, and an error response, so your code handles each shape.
Writing the checks down, even as a short list in a comment or a test, pays off quickly. The next time the API changes a field name or starts returning null where it used to return a string, your list tells you exactly what to re-check instead of forcing you to debug from scratch.
Worked example
| Field | Value | Type |
|---|---|---|
| id | 42 | Number |
| name | Ada | String |
| ada@example.com | String | |
| active | true | Boolean |
| tags | ["beta", "editor"] | Array of strings |
| Trap 1 | id returned as "42" | Syntax check passes, type check catches it |
| Trap 2 | tags returned as null | Code looping over tags without a null check fails |
Consider a small API response for a user record. At first glance it looks fine, but validation should still confirm the details:
{
"id": 42,
"name": "Ada",
"email": "ada@example.com",
"active": true,
"tags": ["beta", "editor"]
}
Here, the checks are straightforward: the top level is an object, id is a number, name and email are strings, active is a boolean, and tags is an array of strings. If the API later returned id as the string “42” instead of the number 42, a syntax check would still pass, but a type check would catch the change before your code compared it with a number and got a surprising result. Similarly, if tags came back as null for a user with no tags, code that loops over tags without a null check would fail. Validation is what turns these quiet changes into visible, fixable findings.
Use the formatter to separate syntax errors from schema errors
Use the formatter to separate syntax errors from schema errors. A parser can confirm that a document is JSON without confirming that it contains the fields your application expects. When the formatter reports the document as valid but your application still behaves oddly, the problem is usually in the schema: a missing field, a renamed key, a different nesting level, or a type that changed. When the formatter reports a syntax error, fix the syntax first, because no schema conclusion is reliable until the document parses.
When an error is reported, inspect the character near the reported location
When an error is reported, inspect the character near the reported location. Common causes include trailing commas, single-quoted strings, unescaped control characters, and missing closing brackets. Parsers often report the position where they gave up, which can be one character after the real mistake, so look slightly before the reported position as well. Other frequent causes include comments copied from documentation, which JSON does not allow, and a missing comma between two object entries. Fixing one error and re-validating is usually faster than trying to fix several at once, because the first error can hide later ones.
Common errors and what they mean
An Unexpected token message usually means the parser found a character it did not expect at that point, such as a single quote where a double quote was required, or a word like undefined where a value was expected. A trailing comma error means there is a comma after the last item in an object or array, which JSON does not permit even though some other formats allow it. An unterminated string error means a string was never closed, often because a quote inside the string was not escaped, or because a line break split the string. A missing bracket or brace error means the nesting was never closed, and the parser reached the end of the document while still expecting more input. Reading the message together with the reported position usually points to one of these cases, and a formatter that highlights the area makes the fix much easier to see.
Limitations: what validation cannot prove
Validation can confirm that a payload is well-formed and matches the shape you checked, but it cannot prove that the data is true, complete, or safe. A valid response can still contain stale values, a wrong user id, or an amount in the wrong currency. Validation also cannot prove that the API will keep returning the same shape; providers change fields, deprecate endpoints, and add new values, so checks need to be re-run when behaviour changes. Finally, validation of a single example does not prove that every response is valid. Edge cases such as empty results, very large payloads, and error responses deserve their own checks, because those are the cases most likely to break code that was only tested on a tidy example.
Do not paste credentials, access tokens, or private customer data into an online utility
Do not paste credentials, access tokens, or private customer data into an online utility. For sensitive payloads, use a local editor or an internal development environment. Before pasting any response, remove tokens, passwords, personal details, and internal identifiers, or replace them with placeholder values. The structure and types stay the same, but the sensitive content does not leave your machine.
Use the related tool carefully
This guide is paired with a browser-only utility. The tool is a practical aid for small examples and inspection; it is not a substitute for application testing, a formal data pipeline, or professional review where the decision has higher consequences.
Open the related JSON Formatter and Validator
Frequently asked questions
Does valid JSON mean the API response is correct?
No. Validity means the document follows JSON syntax and can be parsed. Correctness is a separate question: the payload must also have the fields, types, and values your application expects. Always check structure and content after the syntax check passes.
Why does my code fail even though the JSON is valid?
The most common reasons are a shape mismatch, a renamed or missing field, a type change such as a number arriving as a string, or a null where your code expected an object or array. Compare the actual response field by field against what your code assumes, and add a check for each assumption that turned out to be wrong.
How do I validate JSON without pasting sensitive data online?
Use a local editor, a command-line tool, or your programming language built-in JSON parser on your own machine. If you need to use a browser utility for the structure, redact tokens and personal data first and replace them with placeholders that keep the same types and shapes.
Should I validate JSON on the client, the server, or both?
Validate wherever a bad payload could cause harm. Client-side checks give fast feedback and clearer error messages, while server-side checks protect stored data and downstream systems from anything the client missed. The two checks can share the same list of required fields and types, so they stay consistent.
Sources
- https://www.json.org/json-en.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Try a Tool
Free, in your browser — no sign-up.
- .htaccess Generator Open tool →
- Age Calculator Open tool →
- Angle Converter Open tool →
- API Tester Open tool →
- ASCII Converter Open tool →
- Base64 Encoder and Decoder This tool converts text to the Base64 representation used in many transport and test contexts, and it reverses Base64 text back into Unicode text when the input is valid. Open tool →
Related Articles
How to Format XML So It Is Easy to Read
Learn how to format XML so it is easy to read: consistent indentation, one element per line, matched tags, unchanged data, and…
Read article →How to Build a Query String Without Breaking Your Link
Build a query string without breaking your link. Learn ?key=value, the & separator, encoding, a worked example, and why secrets stay out…
Read article →How to Convert Base64 Back to an Image
Learn how to convert Base64 back to an image, read a data URI, decode a 1 by 1 PNG example, check the…
Read article →