# Validate JSON responses

Use this when you need Ky to parse a JSON response and verify its shape before your code uses it.

## Validate with a Standard Schema

Pass a Standard Schema-compatible validator to `.json()`. The returned promise resolves to the validator's output type; if validation fails, Ky rejects it with a `SchemaValidationError` that carries the validator's issues.

1. Install Ky and a compatible validator. Ky's documentation uses Zod 3.24 or later.

   ```bash
   npm install ky zod
   ```

2. Define the schema and pass it to [`ky`](https://bench-ky-6l.atloria.app/p/bench-ky-6l-QSDF7DxJ6h/developer/ky#default)'s `.json()` method. This browser example requests your same-origin `/api/user` endpoint; with a response matching the schema, it logs the validated user object.

   ```ts
   import ky, {HTTPError, SchemaValidationError, isKyError} from 'ky';
   import {z} from 'zod';

   const userSchema = z.object({name: z.string()});

   const loadUser = async (): Promise<void> => {
    try {
     const user = await ky('/api/user').json(userSchema);
     console.log(user);
    } catch (error: unknown) {
     if (error instanceof SchemaValidationError) {
      console.error('The response did not match the schema:', error.issues);
     } else if (isKyError(error)) {
      if (error instanceof HTTPError) {
       console.error('The request returned an unsuccessful status:', error.response.status);
      } else {
       console.error('Ky request error:', error.message);
      }
     } else {
      throw error;
     }
    }
   };

   void loadUser();
   ```

The schema check runs after Ky has received and parsed the JSON. A matching response resolves with the validated value. A mismatch enters the first error branch with the validator's issues; an unsuccessful HTTP response enters the Ky error handling instead.

## Schema argument

| Argument | Type | Default | Effect |
| --- | --- | --- | --- |
| `schema` | Standard Schema-compatible validator | No schema | Validates the parsed JSON and types the resolved value as the schema's output. Without a schema, `.json()` parses JSON without schema validation. |

## Pitfall: schema errors are not Ky errors

For the error-type distinctions, see [How Ky works](https://bench-ky-6l.atloria.app/p/bench-ky-6l-QSDF7DxJ6h/developer/how-ky-works); this page focuses on reporting the validator's issues when response data fails the schema.

## Related

- [Send and read JSON](https://bench-ky-6l.atloria.app/p/bench-ky-6l-QSDF7DxJ6h/developer/send-and-read-json)
- [Ky errors and validation](https://bench-ky-6l.atloria.app/p/bench-ky-6l-QSDF7DxJ6h/developer/ky-errors-and-validation)
