ネストされたオブジェクト — JSON Schemaで入れ子構造を定義
JSON Schemaでネストされたオブジェクト構造を定義し、階層的なデータをバリデーションする方法を解説します。
Object Constraints
JSON Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 0 }
},
"required": ["name"]
},
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"country": { "type": "string" },
"postalCode": { "type": "string" },
"coordinates": {
"type": "object",
"properties": {
"latitude": { "type": "number", "minimum": -90, "maximum": 90 },
"longitude": { "type": "number", "minimum": -180, "maximum": 180 }
},
"required": ["latitude", "longitude"]
}
},
"required": ["street", "city", "country"]
}
},
"required": ["user", "address"]
}Test Data
{
"user": {
"name": "Alice Chen",
"age": 32
},
"address": {
"street": "123 Main Street",
"city": "San Francisco",
"country": "US",
"postalCode": "94102",
"coordinates": {
"latitude": 37.7749,
"longitude": -122.4194
}
}
}詳細な説明
JSON Schemaではオブジェクトのプロパティ内に別のオブジェクトスキーマを定義することで、ネストされた(入れ子の)データ構造をバリデーションできます。
基本的なネスト構造:
{
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"name": { "type": "string" },
"address": {
"type": "object",
"properties": {
"city": { "type": "string" },
"zip": { "type": "string" }
}
}
}
}
}
}
深くネストされたスキーマは読みにくくなるため、$ref と $defs(旧 definitions)を使用してスキーマを分割・再利用することが推奨されます。これにより、スキーマの保守性と可読性が大幅に向上します。
ユースケース
ユーザープロファイル、注文データ、組織構造など、階層的なJSONデータをバリデーションする際に使用します。