JSON Schema 이해하기: 완벽한 가이드 2026
JSON Schema로 데이터를 검증하고 문서화하는 방법을 배우세요. 기본부터 고급 패턴까지 다루는 종합 가이드입니다.
Big JSON Team
• Technical WriterExpert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.
# JSON Schema 이해하기: 완벽한 가이드 2026
JSON Schema는 JSON 데이터의 구조, 내용 및 의미를 설명하는 강력한 도구입니다. 이 가이드는 기본부터 고급 패턴까지 JSON Schema의 모든 것을 다룹니다.
JSON Schema란?
JSON Schema는 JSON 데이터의 유효성을 검사하기 위한 어휘입니다. 데이터가 특정 요구 사항을 충족하는지 확인하는 계약 역할을 합니다.
기본 예제
스키마:{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number",
"minimum": 0
}
},
"required": ["name", "age"]
}
유효한 데이터:
{
"name": "홍길동",
"age": 30
}
유효하지 않은 데이터:
{
"name": "홍길동"
}
// 오류: 'age'가 필요합니다
기본 타입
string
{
"type": "string",
"minLength": 1,
"maxLength": 100
}
number
{
"type": "number",
"minimum": 0,
"maximum": 100,
"multipleOf": 5
}
integer
{
"type": "integer",
"minimum": 0,
"exclusiveMaximum": 150
}
boolean
{
"type": "boolean"
}
array
{
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}
object
{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name"]
}
문자열 패턴
형식
{
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email"
},
"website": {
"type": "string",
"format": "uri"
},
"birthday": {
"type": "string",
"format": "date"
},
"createdAt": {
"type": "string",
"format": "date-time"
}
}
}
정규식
{
"type": "object",
"properties": {
"phone": {
"type": "string",
"pattern": "^\d{3}-\d{4}-\d{4}$"
},
"zipCode": {
"type": "string",
"pattern": "^\d{5}$"
}
}
}
숫자 제약
{
"type": "object",
"properties": {
"age": {
"type": "integer",
"minimum": 0,
"maximum": 120
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
"discount": {
"type": "number",
"minimum": 0,
"maximum": 100,
"multipleOf": 5
}
}
}
배열 스키마
단일 타입 배열
{
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"maxItems": 5,
"uniqueItems": true
}
튜플 (고정 순서)
{
"type": "array",
"prefixItems": [
{"type": "string"},
{"type": "number"},
{"type": "boolean"}
],
"items": false
}
유효:
["홍길동", 30, true]
객체 배열
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"}
},
"required": ["id", "name"]
}
}
객체 스키마
속성
{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name"],
"additionalProperties": false
}
중첩된 객체
{
"type": "object",
"properties": {
"name": {"type": "string"},
"address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"},
"zipCode": {"type": "string"}
},
"required": ["city"]
}
}
}
패턴 속성
{
"type": "object",
"patternProperties": {
"^S_": {"type": "string"},
"^I_": {"type": "integer"}
}
}
유효:
{
"S_name": "홍길동",
"S_city": "서울",
"I_age": 30,
"I_id": 123
}
조건부 스키마
enum
{
"type": "string",
"enum": ["red", "green", "blue"]
}
const
{
"type": "string",
"const": "active"
}
anyOf (OR)
{
"anyOf": [
{"type": "string"},
{"type": "number"}
]
}
oneOf (XOR)
{
"oneOf": [
{
"type": "object",
"properties": {
"type": {"const": "credit_card"},
"cardNumber": {"type": "string"}
},
"required": ["type", "cardNumber"]
},
{
"type": "object",
"properties": {
"type": {"const": "bank_transfer"},
"accountNumber": {"type": "string"}
},
"required": ["type", "accountNumber"]
}
]
}
allOf (AND)
{
"allOf": [
{
"type": "object",
"properties": {
"name": {"type": "string"}
}
},
{
"type": "object",
"properties": {
"age": {"type": "number"}
}
}
]
}
not
{
"not": {
"type": "string"
}
}
if-then-else
{
"type": "object",
"properties": {
"country": {"type": "string"}
},
"if": {
"properties": {
"country": {"const": "한국"}
}
},
"then": {
"properties": {
"zipCode": {
"type": "string",
"pattern": "^\d{5}$"
}
}
},
"else": {
"properties": {
"zipCode": {"type": "string"}
}
}
}
재사용 ($ref, $defs)
{
"$defs": {
"address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"}
},
"required": ["city"]
}
},
"type": "object",
"properties": {
"name": {"type": "string"},
"homeAddress": {"$ref": "#/$defs/address"},
"workAddress": {"$ref": "#/$defs/address"}
}
}
실용적인 예제
사용자 스키마
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/user.schema.json",
"title": "User",
"description": "사용자 스키마",
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "사용자 ID"
},
"username": {
"type": "string",
"minLength": 3,
"maxLength": 20,
"pattern": "^[a-zA-Z0-9_]+$"
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 13,
"maximum": 120
},
"roles": {
"type": "array",
"items": {
"type": "string",
"enum": ["user", "admin", "moderator"]
},
"uniqueItems": true,
"minItems": 1
},
"profile": {
"type": "object",
"properties": {
"firstName": {"type": "string"},
"lastName": {"type": "string"},
"bio": {
"type": "string",
"maxLength": 500
}
}
},
"createdAt": {
"type": "string",
"format": "date-time"
}
},
"required": ["id", "username", "email"],
"additionalProperties": false
}
제품 스키마
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Product",
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 1
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"description": {
"type": "string",
"maxLength": 1000
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
"currency": {
"type": "string",
"enum": ["USD", "EUR", "KRW", "JPY"]
},
"stock": {
"type": "integer",
"minimum": 0
},
"categories": {
"type": "array",
"items": {"type": "string"},
"uniqueItems": true
},
"tags": {
"type": "array",
"items": {"type": "string"}
},
"availability": {
"type": "string",
"enum": ["in_stock", "out_of_stock", "preorder"]
}
},
"required": ["id", "name", "price", "currency"]
}
검증 구현
JavaScript (ajv)
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "number", minimum: 0 }
},
required: ["name", "age"]
};
const validate = ajv.compile(schema);
// 검증
const data = { name: "홍길동", age: 30 };
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
} else {
console.log("유효한 데이터!");
}
Python (jsonschema)
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0}
},
"required": ["name", "age"]
}
data = {"name": "홍길동", "age": 30}
try:
validate(instance=data, schema=schema)
print("유효한 데이터!")
except ValidationError as e:
print(f"검증 오류: {e.message}")
Pydantic (Python)
from pydantic import BaseModel, Field, EmailStr
from typing import List
class User(BaseModel):
id: int = Field(ge=1)
username: str = Field(min_length=3, max_length=20)
email: EmailStr
age: int = Field(ge=13, le=120)
roles: List[str]
# 자동 검증
try:
user = User(
id=1,
username="hong",
email="hong@example.com",
age=30,
roles=["user", "admin"]
)
print(user.json(indent=2, ensure_ascii=False))
except Exception as e:
print(f"검증 오류: {e}")
모범 사례
1. 명확한 설명 추가
{
"type": "object",
"properties": {
"age": {
"type": "integer",
"minimum": 0,
"description": "사용자의 나이 (년)"
}
}
}
2. 기본값 정의
{
"type": "object",
"properties": {
"role": {
"type": "string",
"default": "user",
"enum": ["user", "admin"]
}
}
}
3. 예제 포함
{
"type": "string",
"format": "email",
"examples": [
"user@example.com",
"admin@company.com"
]
}
4. additionalProperties 사용
{
"type": "object",
"properties": {
"name": {"type": "string"}
},
"additionalProperties": false
}
결론
JSON Schema는 데이터 검증, 문서화 및 타입 안전성을 위한 강력한 도구입니다. API 개발, 구성 관리 또는 데이터 파이프라인에서 JSON Schema는 데이터 품질과 일관성을 보장합니다.
주요 요점:- ✓ 타입 및 제약 조건 정의
- ✓ 재사용 가능한 스키마 생성
- ✓ 명확한 오류 메시지
- ✓ 문서화 및 예제 포함
- ✓ 적절한 라이브러리 사용
JSON Schema로 견고한 애플리케이션을 구축하세요!
관련 글
JSON이란 무엇인가? JavaScript Object Notation 완벽 가이드
JSON(JavaScript Object Notation)의 기본 개념부터 실제 활용까지. 웹 개발의 필수 데이터 형식인 JSON을 완벽하게 이해해보세요.
JSON을 TypeScript로 변환: 타입 안정성의 완벽 가이드
JSON 데이터에서 TypeScript 타입과 인터페이스를 자동 생성하는 모든 방법을 배워보세요. 도구, 기법, 모범 사례까지 완벽 정리.
일반적인 JSON 오류와 해결 방법: 완벽 디버깅 가이드
JSON 파싱 오류를 빠르게 찾고 수정하는 방법을 배워보세요. 일반적인 실수, 디버깅 도구, 예방 방법까지 완벽 정리.