JSON Schema Validation คืออะไร?
JSON Schema validation คือกระบวนการตรวจสอบว่าเอกสาร JSON เป็นไปตามชุดข้อกำหนดด้านโครงสร้างและค่าที่กำหนดไว้ใน JSON Schema หรือไม่ ตัว schema เองก็เป็นเอกสาร JSON ที่อธิบายรูปแบบที่คาดหวังของข้อมูล: ระบุว่า property ใดบ้างที่จำเป็น ชนิดข้อมูลที่ต้องเป็น ช่วงค่าที่อนุญาตสำหรับตัวเลข รูปแบบสตริง ความยาวของอาร์เรย์ และอื่นๆ ข้อกำหนด JSON Schema ดูแลโดย json-schema.org และเผยแพร่เป็น IETF draft หลายชุด โดย Draft 7 และ Draft 2020-12 ได้รับการนำไปใช้อย่างแพร่หลายที่สุด
การตรวจสอบ JSON แบบทั่วไปจะตรวจสอบเพียงไวยากรณ์เท่านั้น (วงเล็บปิดครบไหม? สตริงมีเครื่องหมายอัญประกาศไหม?) แต่การตรวจสอบด้วย schema ก้าวไปอีกขั้น โดยตอบคำถามเช่น: การตอบสนองจาก API นี้มีฟิลด์ "id" ที่เป็นจำนวนเต็มเสมอไหม? ฟิลด์ "status" เป็นหนึ่งในสามค่าที่อนุญาตไหม? ออบเจกต์ที่ซ้อนอยู่มีโครงสร้างถูกต้องไหม? การตรวจสอบโครงสร้างในลักษณะนี้ช่วยจับข้อผิดพลาดที่การตรวจสอบไวยากรณ์พลาดไปโดยสิ้นเชิง เพราะ JSON ที่ถูกต้องทางไวยากรณ์ก็อาจผิดในเชิงความหมายสำหรับแอปพลิเคชันของคุณได้
JSON Schema ถูกใช้งานในนิยาม OpenAPI/Swagger การตรวจสอบไฟล์คอนฟิก การตรวจสอบฟอร์ม ข้อกำหนดเอกสารในฐานข้อมูล และการทดสอบอัตโนมัติ เครื่องมืออย่าง Ajv (JavaScript), jsonschema (Python) และ check-jsonschema (CLI) นำข้อกำหนดนี้ไปใช้งานเพื่อให้คุณตรวจสอบข้อมูลได้ตามโปรแกรม ตัวตรวจสอบออนไลน์นี้ช่วยให้คุณวาง schema และเอกสารข้อมูลเพื่อตรวจสอบความสอดคล้องได้ทันที โดยไม่ต้องติดตั้งไลบรารีใดๆ
ทำไมต้องใช้ JSON Schema Validator ออนไลน์?
การเขียน schema และแก้จุดบกพร่องของข้อผิดพลาดการตรวจสอบด้วยตนเองนั้นช้า JSON Schema validator ออนไลน์ให้ผลตอบรับทันทีว่าข้อมูลของคุณตรงกับ schema หรือไม่ พร้อมข้อความแสดงข้อผิดพลาดที่ชี้ชัดไปยัง property ที่ล้มเหลว
กรณีการใช้งาน JSON Schema Validation
อ้างอิง Keyword ของ JSON Schema
JSON Schema ถูกสร้างขึ้นจาก keyword ที่แต่ละตัวกำหนดข้อจำกัดบนข้อมูลที่ตรวจสอบ ตารางด้านล่างแสดง keyword ที่ใช้บ่อยที่สุดใน Draft 7 และรุ่นหลังจากนั้น keyword ทุกตัวสามารถใช้ร่วมกับตัวอื่นในออบเจกต์ schema เดียวกันได้
| Keyword | วัตถุประสงค์ | ตัวอย่าง |
|---|---|---|
| type | Restricts the data type | "type": "string" |
| properties | Defines expected object keys and their schemas | "properties": { "name": { "type": "string" } } |
| required | Lists mandatory properties | "required": ["id", "name"] |
| items | Schema for array elements | "items": { "type": "number" } |
| enum | Restricts value to a fixed set | "enum": ["active", "inactive"] |
| pattern | Regex constraint on strings | "pattern": "^[A-Z]{2}\\d{4}$" |
| minimum / maximum | Numeric range bounds | "minimum": 0, "maximum": 100 |
| minLength / maxLength | String length bounds | "minLength": 1, "maxLength": 255 |
| $ref | Reuses another schema by URI | "$ref": "#/$defs/address" |
| additionalProperties | Controls extra keys in objects | "additionalProperties": false |
| anyOf / oneOf / allOf | Combines multiple schemas logically | "anyOf": [{ "type": "string" }, { "type": "null" }] |
| if / then / else | Conditional schema application | "if": { "properties": { "type": { "const": "email" } } } |
เปรียบเทียบ JSON Schema Draft: Draft 7 vs 2019-09 vs 2020-12
JSON Schema ผ่านการพัฒนามาหลาย draft Draft 7 (เผยแพร่ปี 2018) ได้รับการสนับสนุนจากเครื่องมือต่างๆ อย่างกว้างขวางที่สุด Draft 2019-09 แนะนำ $defs (แทนที่ definitions), unevaluatedProperties และ $recursiveRef Draft 2020-12 (เวอร์ชันเสถียรล่าสุด) แทนที่ $recursiveRef ด้วย $dynamicRef และแนะนำ prefixItems สำหรับการตรวจสอบ tuple เมื่อเลือก draft ให้ตรวจสอบว่าไลบรารีที่ใช้รองรับ Ajv รองรับทั้งสาม draft ส่วนไลบรารี jsonschema ของ Python รองรับจนถึง 2020-12 ตั้งแต่เวอร์ชัน 4.0
| คุณสมบัติ | Draft 7 | Draft 2019-09 | Draft 2020-12 |
|---|---|---|---|
| $schema URI | draft-07/schema# | 2019-09/schema | 2020-12/schema |
| if / then / else | Yes | Yes | Yes |
| $defs (definitions) | definitions | $defs | $defs |
| $ref alongside keys | No (sibling ignored) | Yes | Yes |
| $dynamicRef | No | No ($recursiveRef) | Yes |
| prefixItems | No (use items array) | No (use items array) | Yes |
| unevaluatedProperties | No | Yes | Yes |
| $vocabulary | No | Yes | Yes |
ตัวอย่างโค้ด
ตัวอย่างเหล่านี้แสดงวิธีตรวจสอบ JSON กับ schema ตามโปรแกรม แต่ละตัวอย่างใช้ไลบรารีที่ได้รับการดูแลรักษาดีในระบบนิเวศภาษานั้นๆ
import Ajv from 'ajv';
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
age: { type: 'integer', minimum: 0 },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email'],
additionalProperties: false
};
const data = { name: 'Alice', age: 30, email: 'alice@example.com' };
const validate = ajv.compile(schema);
const valid = validate(data);
console.log(valid); // → true
console.log(validate.errors); // → null
// Invalid data — missing required "email"
validate({ name: 'Bob', age: 25 });
console.log(validate.errors);
// → [{ instancePath: '', keyword: 'required', params: { missingProperty: 'email' } }]from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"age": {"type": "integer", "minimum": 0},
"tags": {
"type": "array",
"items": {"type": "string"},
"uniqueItems": True
}
},
"required": ["name"]
}
# Valid data
validate(instance={"name": "Alice", "age": 30, "tags": ["admin"]}, schema=schema)
# → No exception raised
# Invalid data — wrong type for "age"
try:
validate(instance={"name": "Alice", "age": "thirty"}, schema=schema)
except ValidationError as e:
print(e.message)
# → 'thirty' is not of type 'integer'
print(e.json_path)
# → $.agepackage main
import (
"fmt"
"strings"
"github.com/santhosh-tekuri/jsonschema/v5"
)
func main() {
schemaJSON := `{
"type": "object",
"properties": {
"id": { "type": "integer" },
"status": { "enum": ["active", "inactive"] }
},
"required": ["id", "status"]
}`
compiler := jsonschema.NewCompiler()
compiler.AddResource("schema.json", strings.NewReader(schemaJSON))
schema, _ := compiler.Compile("schema.json")
// Valid data
data := map[string]interface{}{"id": 1, "status": "active"}
err := schema.Validate(data)
fmt.Println(err) // → <nil>
// Invalid — missing "status"
bad := map[string]interface{}{"id": 2}
err = schema.Validate(bad)
fmt.Println(err) // → validation failed: missing properties: 'status'
}# Install via pip pip install check-jsonschema # Validate a file against a schema check-jsonschema --schemafile schema.json data.json # → ok -- validation done # Validate against a remote schema (e.g., GitHub Actions workflow) check-jsonschema --builtin-schema vendor.github-workflows my-workflow.yml # Validate multiple files at once check-jsonschema --schemafile schema.json file1.json file2.json file3.json