JSON Schema

JSON Schema 是一個可以用來檢查 JSON 格式是否符合預期的套件。

安裝

pip install jsonschema

基本使用

使用 validate 函式來檢查資料是否符合 Schema。

from jsonschema import validate, ValidationError

# 定義預期的資料結構
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "number"},
    },
}

data = {
    "name": "Allen",
    "age": 30,
}

try:
    # 判斷 data 的結構是否與 schema 的相同
    # 如果與 schema 不同,就會拋出例外
    validate(instance=data, schema=schema)
    print("Validation successful")
except ValidationError as e:
    print(f"Validation failed: {e}")

定義 Schema

在結構定義中,我們需要先使用 type 定義我們預期的型別,以簡單的字串、數字、列表與物件為例。

檢查字串與數字 (String and Number)

  • type: 指定資料型態,如 "string", "number" (包含整數與浮點數)。
  • 字串可以使用 minLength, maxLength, pattern (Regex) 來限制。
  • 數字可以使用 minimum, maximum, exclusiveMinimum, exclusiveMaximum 來限制範圍。
schema = {
    "type": "object",
    "properties": {
        "username": {
            "type": "string",
            "minLength": 3,
            "maxLength": 20
        },
        "email": {
            "type": "string",
            "pattern": r"^\\S+@\\S+\\.\\S+$"
        },
        "age": {
            "type": "number",
            "minimum": 0,
            "maximum": 120
        },
    }
}

檢查列表 (List)

  • type: 設定為 "array"
  • items: 定義列表內元素的 Schema。
schema = {
    "type": "object",
    "properties": {
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "scores": {
            "type": "array",
            "items": {
                "type": "number"
            },
            "minItems": 1,
            "maxItems": 10,
            "uniqueItems": True
        }
    }
}

檢查物件 (Object)

  • type: 設定為 "object"
  • properties: 定義物件內各個屬性的 Schema。
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"},
        "email": {"type": "string"}
    }
}

定義必填欄位 (Required)

  • required: 一個包含必填欄位名稱的列表。必須定義在該欄位所屬的物件層級。
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "email": {"type": "string"},
        "age": {"type": "integer"}
    },
    "required": ["name", "email"]
}

巢狀物件 (Nested Object)

可以將上述概念組合,定義多層次的巢狀結構。

schema = {
    "type": "object",
    "properties": {
        "id": {"type": "integer"},
        "user": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "email": {"type": "string"}
            },
            "required": ["name"]
        }
    },
    "required": ["id", "user"]
}

參考資料


This site uses Just the Docs, a documentation theme for Jekyll.