如何第一時間看到新文章?
收藏本部落格列表頁,並在首頁與工具聚合頁留意指南入口。閱讀文章無需註冊或訂閱電子報。
透過可直接使用的範例掌握必填欄位、巢狀物件、陣列、列舉、可重用定義與條件驗證,建立清楚可維護的資料契約。
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 應維持可讀。完整工作流程、權限或庫存邏輯應留在應用層。
致力於為開發者提供最佳的 JSON 處理工具
更多文章即將發布...
返回部落格關於跟進更新、選題與互動方式。
收藏本部落格列表頁,並在首頁與工具聚合頁留意指南入口。閱讀文章無需註冊或訂閱電子報。
圍繞 JSON 驗證、格式化、轉換與除錯流程,以及 JSON Work 工具更新,與站內工具的本地能力互相呼應。
可以。請透過關於頁的聯絡方式或 GitHub 回饋;我們會優先安排貼近真實開發情境的教學。