Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท JSON

Validating JSON Data

Never trust API data. Write hand-made validators and type guards, learn the core ideas of JSON Schema, and run a pinned Ajv validator from a CDN.

JSON.parse only checks syntax. It happily accepts {"age": "banana"}, because that is perfectly valid JSON. Whether age should be a number, whether it may be missing, or whether the whole response is really a user and not an error page is a separate question, and the parser cannot answer it.

Data from a network is untrusted input. The server might have a bug, the API might change next month, a proxy might return an HTML error page, or an attacker might send something unexpected. If you let such data flow into your code unchecked, the failure shows up far away from the cause: undefined is not a function in a rendering helper, or a total that shows NaN. Validating at the boundary, right after parsing, keeps the rest of your program simple because everything inside can rely on the shape.

This lesson builds validation in three layers: hand-written checks, reusable type guards, and a declarative schema checked by a library.

Syntax is not shape

Start with a response that parses fine but is wrong in three different ways.

JS Valid JSON, invalid data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

None of these lines throws, which is the dangerous part. The second record has a string id, the third prints UNDEFINED, and the last one produces NaN. Bad data silently turned into bad output.

A hand-written validator

The simplest validator is a function that checks what you need and returns a list of problems. Returning all problems (not just the first) makes debugging far easier.

JS Collecting every problem

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice what the checks look at:

  • typeof null is "object", so the object test excludes null explicitly.
  • Arrays are objects too, so they are excluded separately.
  • Number.isInteger rejects strings, NaN and 1.5 in one go. A plain typeof x === 'number' would accept NaN.
  • An optional field is checked only when it is present.

Type guards

In plain JavaScript a validator returns booleans or error lists. In TypeScript the same idea becomes a type guard: a function whose return type tells the compiler "if I return true, the value has this type". The code inside the function is identical to what you already wrote; only the signature changes.

TypeScript
type User = { id: number; name: string; age?: number };

function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' && value !== null &&
    Number.isInteger((value as User).id) &&
    typeof (value as User).name === 'string'
  );
}

const data: unknown = JSON.parse(text);
if (isUser(data)) {
  data.name.toUpperCase(); // data is a User here
}

The key habit is that JSON.parse returns any. Treat its result as unknown and make it earn a type by passing a guard. Casting with as User without checking only silences the compiler and checks nothing at runtime.

Composing small checks

Writing every check by hand gets repetitive. A few small helpers that return a problem string (or null) let you describe a shape in a table-like way.

JS Small composable checks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first call prints an empty array: no problems. The second reports one message per bad field. This small design already shows how libraries work: a description of the shape plus a generic engine that walks the data.

What JSON Schema is

JSON Schema is a standard, language-independent way to describe JSON shapes. A schema is itself a JSON document, so the same description can be shared between a Node server, a browser, a Python test suite and your API documentation. You describe constraints with keywords:

Keyword Meaning
type object, array, string, number, integer, boolean, null
properties A schema for each named key of an object
required Keys that must be present
additionalProperties Whether unknown keys are allowed (false forbids them)
minimum, maximum Numeric range
minLength, maxLength, pattern String length and regular expression
enum The value must equal one of a fixed list
items A schema for every element of an array

Here is the user check from earlier as a schema:

JSON
{
  "type": "object",
  "properties": {
    "id":   { "type": "integer" },
    "name": { "type": "string", "minLength": 1 },
    "age":  { "type": "integer", "minimum": 0, "maximum": 150 }
  },
  "required": ["id", "name"],
  "additionalProperties": false
}
flowchart LR
  A["Response text"] --> B["JSON.parse<br/>(syntax check)"]
  B --> C["Validate<br/>(shape check)"]
  C -->|valid| D["Use the data"]
  C -->|invalid| E["Report errors<br/>show fallback UI"]

Validate right after parsing so the rest of the program only sees data it can rely on.

Schemas are a contract. They also give you generated documentation, test fixtures, and the same rules on client and server. The trade-off is an extra dependency and a little learning; for two or three fields, a hand-written check is perfectly fine.

Running a validator from a CDN

There are many JSON Schema libraries. Ajv is the most widely used one in JavaScript. The example below loads Ajv 8.17.1 as an ES module from jsDelivr. The version is pinned, so the page keeps working exactly the same tomorrow.

Validating with Ajv from a CDN

You should see the first sample pass, the second fail with one error (/id must be integer), and the third fail with three: a missing name, an age above the maximum and the extra key admin. With allErrors: true, Ajv reports every problem instead of stopping at the first.

Ajv builds a validator by generating JavaScript code, so it needs new Function. If a page's content security policy forbids that, use Ajv's standalone mode at build time, or a library that interprets schemas without code generation.

Where validation belongs

  • At every trust boundary: responses from your own API, third-party APIs, postMessage, URL parameters, and anything read back from storage.
  • On the server, too. Client-side validation improves the experience, but a user can bypass it. The server must always re-check what it receives (see AJAX Security).
  • With a plan for failure. Decide what the UI does with invalid data: show an error state, use a safe default, or log the problem. Do not swallow it silently.
  • Not forever strict. Allowing unknown extra keys (the default in most validators) lets the API add fields without breaking your app.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does JSON.parse not protect you from wrong data?

    Parsing verifies the text is well-formed JSON. Whether the values have the shape your program expects is a separate validation step.
  2. 2. Which check correctly rejects NaN, strings and 1.5 when you need a whole number?

    typeof NaN is 'number', so it passes the first test. Number.isInteger is false for NaN, non-numbers and fractions.
  3. 3. In JSON Schema, which keyword makes a key mandatory?

    required lists the keys that must be present. properties only describes the shape of keys that do appear.
  4. 4. Why should you also validate on the server when the client already validates?

    Client validation is a convenience. Anyone can call your API without your front end, so the server is the authority.

Summary

  • JSON.parse checks syntax only; treat parsed data as untrusted unknown until validated.
  • Validate right after parsing, at the boundary, and collect every problem, not just the first.
  • Use Number.isInteger, explicit null and array checks, and check optional fields only when present.
  • In TypeScript, a type guard turns a runtime check into a compile-time type; as alone checks nothing.
  • JSON Schema describes shapes declaratively with keywords like type, properties, required and enum.
  • Libraries such as Ajv run schemas for you; pin the CDN version and keep server-side validation as the authority.

Next: Your First fetch() Request.