JSON Schema 検証完全ガイド:データ検証・ドキュメント生成・コード補完を一体化

JSON Schema:データの契約

JSON Schema は JSON データの構造定義言語です。JavaScript における TypeScript のような存在ですが、ランタイム検証や言語横断のシナリオに適用できます。

用途 説明
データ検証 API リクエスト/レスポンスの検証
ドキュメント生成 API ドキュメントの自動生成
IDE ヒント VS Code のスマート補完
モックデータ テストデータの自動生成
設定検証 package.json、tsconfig.json など

一、基本型

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1, "maxLength": 100 },
    "age": { "type": "integer", "minimum": 0, "maximum": 150 },
    "email": { "type": "string", "format": "email" },
    "isActive": { "type": "boolean" },
    "score": { "type": "number", "minimum": 0, "maximum": 100 },
    "tags": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 1,
      "maxItems": 10,
      "uniqueItems": true
    }
  },
  "required": ["name", "email"],
  "additionalProperties": false
}

組み込みフォーマット

format マッチングルール 例
email RFC 5322 user@example.com
uri URI https://example.com
date ISO 8601 日付 2026-06-02
time ISO 8601 時刻 14:30:00
date-time ISO 8601 日時 2026-06-02T14:30:00Z
ipv4 IPv4 アドレス 192.168.1.1
ipv6 IPv6 アドレス ::1
uuid UUID 550e8400-e29b-41d4-a716-446655440000
hostname ホスト名 example.com

二、高度なパターン

ネストされたオブジェクト

{
  "type": "object",
  "properties": {
    "user": {
      "type": "object",
      "properties": {
        "profile": {
          "type": "object",
          "properties": {
            "avatar": { "type": "string", "format": "uri" },
            "bio": { "type": "string", "maxLength": 200 }
          }
        }
      }
    }
  }
}

列挙型とユニオン型

{
  "status": {
    "type": "string",
    "enum": ["pending", "active", "completed", "cancelled"]
  },
  "id": {
    "oneOf": [
      { "type": "string", "format": "uuid" },
      { "type": "integer", "minimum": 1 }
    ]
  }
}

条件付き検証

{
  "type": "object",
  "properties": {
    "paymentMethod": { "type": "string", "enum": ["credit_card", "bank_transfer"] },
    "cardNumber": { "type": "string" },
    "bankAccount": { "type": "string" }
  },
  "if": {
    "properties": { "paymentMethod": { "const": "credit_card" } }
  },
  "then": {
    "required": ["cardNumber"],
    "properties": { "cardNumber": { "pattern": "^\\d{16}$" } }
  },
  "else": {
    "required": ["bankAccount"]
  }
}

正規表現パターン

{
  "phone": { "type": "string", "pattern": "^1[3-9]\\d{9}$" },
  "postalCode": { "type": "string", "pattern": "^\\d{6}$" },
  "slug": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }
}

三、$ref と定義の再利用

{
  "$defs": {
    "address": {
      "type": "object",
      "properties": {
        "street": { "type": "string" },
        "city": { "type": "string" },
        "zipCode": { "type": "string", "pattern": "^\\d{6}$" }
      },
      "required": ["street", "city", "zipCode"]
    }
  },
  "type": "object",
  "properties": {
    "homeAddress": { "$ref": "#/$defs/address" },
    "workAddress": { "$ref": "#/$defs/address" }
  }
}

四、ランタイム検証

Ajv(最速のバリデーター)

import Ajv from 'ajv';

const ajv = new Ajv({ allErrors: true, strict: false });

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string', minLength: 1 },
    age: { type: 'integer', minimum: 0 },
  },
  required: ['name', 'age'],
};

const validate = ajv.compile(schema);

const valid = validate({ name: '张三', age: 25 });
if (!valid) {
  console.log(validate.errors);
  // [{ keyword: 'minimum', dataPath: '/age', message: 'must be >= 0' }]
}

Zod(TypeScript ファースト)

import { z } from 'zod';

const UserSchema = z.object({
  name: z.string().min(1).max(100),
  age: z.number().int().min(0).max(150),
  email: z.string().email(),
  tags: z.array(z.string()).min(1).max(10),
});

// 型は自動で推論される
type User = z.infer<typeof UserSchema>;

// 検証
const result = UserSchema.safeParse(input);
if (result.success) {
  console.log(result.data); // 型安全
} else {
  console.log(result.error.issues);
}

五、IDE のスマート補完

VS Code の設定

// .vscode/settings.json
{
  "json.schemas": [
    {
      "fileMatch": ["/config/*.json"],
      "url": "./schemas/config-schema.json"
    },
    {
      "fileMatch": ["package.json"],
      "url": "https://json.schemastore.org/package"
    }
  ]
}

JSON ファイル内で Schema を参照する

{
  "$schema": "./schemas/config-schema.json",
  "name": "my-project"
  // IDE の自動補完・エラー表示
}

Schema Store

Schema Store では 400 以上の一般的な JSON Schema を提供しています:

  • package.json
  • tsconfig.json
  • .eslintrc.json
  • docker-compose.json
  • GitHub Actions workflows

六、JSON から Schema を生成する

ツールを使う方法

  1. JSON 整形ツールを開く
  2. JSON データを貼り付ける
  3. 「Schema を生成」をクリック
  4. 型・列挙・範囲が自動で推論される

コマンドラインツール

# json-schema-generator を使う
npx json-schema-generator sample.json -o schema.json

# quicktype を使う
npx quicktype sample.json -o schema.json --lang schema

七、モックデータ生成

import { faker } from '@faker-js/faker';

// Schema をもとにモックデータを生成
function generateMock(schema) {
  if (schema.type === 'string') {
    if (schema.format === 'email') return faker.internet.email();
    if (schema.format === 'uri') return faker.internet.url();
    if (schema.enum) return faker.helpers.arrayElement(schema.enum);
    return faker.lorem.word();
  }
  if (schema.type === 'integer') return faker.number.int(schema);
  if (schema.type === 'boolean') return faker.datatype.boolean();
  if (schema.type === 'array') {
    return Array.from({ length: 3 }, () => generateMock(schema.items));
  }
  if (schema.type === 'object') {
    const result = {};
    for (const [key, propSchema] of Object.entries(schema.properties)) {
      result[key] = generateMock(propSchema);
    }
    return result;
  }
}

八、ベストプラクティス

  1. 必ず $schema を宣言する:Draft バージョンを指定して曖昧さを回避
  2. additionalProperties: false を使う:未定義のフィールドを禁止
  3. $defs + $ref を使う:共通構造を再利用
  4. 手書きの pattern より format を使う:可読性が高く、バリデーターが自動で処理
  5. CI に検証を組み込む:API レスポンスが常に Schema に準拠することを保証
  6. Schema のバージョン管理:API バージョンと同期し、後方互換性チェックをサポート
#JSON Schema#数据校验#Ajv#Zod#API