教學

JSON Schema 實用範例:物件、陣列、列舉與條件規則

透過可直接使用的範例掌握必填欄位、巢狀物件、陣列、列舉、可重用定義與條件驗證,建立清楚可維護的資料契約。

2026-07-2910 分鐘

JSON Schema 用來描述 JSON 資料的結構與限制。它可以作為 API 契約、設定檔規範與匯入驗證規則,把「status 必須存在」這類約定變成可執行規則。

從物件與必填欄位開始

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["id", "status"],
  "properties": {
    "id": { "type": "string", "minLength": 1 },
    "status": { "enum": ["pending", "active", "disabled"] }
  },
  "additionalProperties": false
}

additionalProperties: false 能找出拼字錯誤與意外欄位,但應謹慎使用。內部 API 與受控設定很適合;需要向後相容的公開 API 可能要允許新欄位。

驗證巢狀物件

{
  "type": "object",
  "required": ["name", "address"],
  "properties": {
    "name": { "type": "string" },
    "address": {
      "type": "object",
      "required": ["country", "postalCode"],
      "properties": {
        "country": { "type": "string", "minLength": 2 },
        "postalCode": { "type": "string", "pattern": "^[A-Za-z0-9 -]+$" }
      },
      "additionalProperties": false
    }
  }
}

正規表示式只能檢查文字形式,不能證明郵遞區號真實存在。國家、庫存與權限等事實仍應由應用程式驗證。

限制陣列與元素

{
  "type": "array",
  "minItems": 1,
  "uniqueItems": true,
  "items": {
    "type": "object",
    "required": ["sku", "quantity"],
    "properties": {
      "sku": { "type": "string", "minLength": 1 },
      "quantity": { "type": "integer", "minimum": 1 }
    },
    "additionalProperties": false
  }
}

uniqueItems 比較完整 JSON 值。如果要依單一欄位判斷唯一,通常需要應用程式或資料庫限制。

使用 $defs 重用定義

{
  "$defs": {
    "money": {
      "type": "object",
      "required": ["amount", "currency"],
      "properties": {
        "amount": { "type": "number", "minimum": 0 },
        "currency": { "type": "string", "pattern": "^[A-Z]{3}$" }
      }
    }
  },
  "type": "object",
  "properties": {
    "subtotal": { "$ref": "#/$defs/money" },
    "total": { "$ref": "#/$defs/money" }
  }
}

需要精確金額時,請明確選擇十進位字串或最小貨幣單位整數,避免浮點數語意不清。

加入條件規則

{
  "type": "object",
  "required": ["deliveryMethod"],
  "properties": {
    "deliveryMethod": { "enum": ["pickup", "shipping"] },
    "shippingAddress": { "type": "string" },
    "pickupLocationId": { "type": "string" }
  },
  "allOf": [
    {
      "if": { "properties": { "deliveryMethod": { "const": "shipping" } } },
      "then": { "required": ["shippingAddress"] },
      "else": { "required": ["pickupLocationId"] }
    }
  ]
}

Schema 應維持可讀。完整工作流程、權限或庫存邏輯應留在應用層。

建議流程

  1. 準備合法與非法樣本。
  1. 使用 JSON Schema 產生器建立基礎結構。
  1. 依真正契約補上 required、邊界與相容性規則。
  1. 測試缺少欄位、錯誤型別、額外欄位與空集合。
  1. 將 Schema 納入版本控制與自動化測試。

JSON Schema 官方入門文件是關鍵字與版本行為的主要參考。產生器能加快第一版,但最終規則必須反映真實業務需求。

Ene Chen

致力於為開發者提供最佳的 JSON 處理工具

相關文章

更多文章即將發布...

返回部落格

相關工具推薦

常見問題

關於跟進更新、選題與互動方式。

如何第一時間看到新文章?

收藏本部落格列表頁,並在首頁與工具聚合頁留意指南入口。閱讀文章無需註冊或訂閱電子報。

部落格主要寫什麼?

圍繞 JSON 驗證、格式化、轉換與除錯流程,以及 JSON Work 工具更新,與站內工具的本地能力互相呼應。

可以建議教學主題嗎?

可以。請透過關於頁的聯絡方式或 GitHub 回饋;我們會優先安排貼近真實開發情境的教學。