본문 바로가기
C.W.K.
Stream
Lesson 02 of 08 · published

type, properties, required — 세 일꾼

~10 min · json-schema, type, properties

Level 0평문
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

모양 선언의 핵심

JSON Schema 로 하는 일의 대부분은 키워드 세 개가 처리해. type 이 JSON 타입을 정하고, properties 가 객체의 키를 정하고, required 가 그중 어느 키가 반드시 있어야 하는지 나열해.

Type 값

type 값은 일곱 개야. JSON 의 여섯 타입에 하나가 더 갈라져 나온 형태지. "string", "number", "integer", "boolean", "null", "object", "array". 여기서 integernumber 아래 갈래야. validator 가 소수 부분이 있는지 없는지를 봐서 갈라줘.

Type union

여러 타입을 허용하려면 type 에 배열을 줘. "type": ["string", "null"] 이면 'string 이거나 null' 이라는 뜻이야. null 을 허용하는 필드에서 제일 흔히 보는 모양이지.

required 는 opt-in

기본값은 '전부 있어도 되고 없어도 됨' 이야. required 에 반드시 있어야 할 property 이름을 배열로 적어줘야 비로소 필수가 돼. required 를 아예 안 쓰면 전부 선택이라서, 텅 빈 객체도 통과해버려.

'required' 는 'properties' 옆에 살지 그 안에 살지 않아. property 안에 required: true 를 넣는 게 흔한 실수야. 그건 Draft-04 문법이고 Draft-06 부터 없어졌어. 요즘 JSON Schema 는 객체 단계에 배열로 적어. "required": ["name", "email"] 이렇게.

Code

필수 + 옵션 필드 가진 객체·json
{
  "type": "object",
  "properties": {
    "id":         { "type": "integer" },
    "name":       { "type": "string" },
    "email":      { "type": "string" },
    "created_at": { "type": "string" },
    "deleted_at": { "type": ["string", "null"] }
  },
  "required": ["id", "name", "email"]
}
중첩 객체 type·json
{
  "type": "object",
  "properties": {
    "user": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "email": { "type": "string" }
      },
      "required": ["name", "email"]
    }
  },
  "required": ["user"]
}
Type union (nullable)·json
{
  "type": "object",
  "properties": {
    "middle_name": { "type": ["string", "null"] }
  }
}

External links

Exercise

최근에 만진 작은 JSON 문서를 하나 골라. API 응답이든 config 든. 그걸 설명하는 JSON Schema 를 처음부터 써봐. type 을 선언하고 필수 필드를 나열하는 거야. 그 다음 validator 를 돌리고 (ajv 나 Python jsonschema), 필드를 하나씩 일부러 깨뜨려. 에러 메시지가 뭐가 어긋났는지 정확히 짚어주는 걸 보게 될 거야.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.