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

배열 — items, uniqueItems, contains

~10 min · json-schema, arrays, items

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

요소, 크기, 배열 내용 제약

items — 모든 요소의 schema

items 에는 schema 를 통째로 넣어. 배열의 모든 요소가 거기 맞아야 해. {"type": "array", "items": {"type": "string"}} 는 '문자열만 든 배열' 이라는 뜻이야.

prefixItems — 튜플 스타일 검증

prefixItems 에 schema 배열을 주면 자리별로 검사해. 0 번 자리는 첫 schema 로, 1 번 자리는 두 번째 schema 로 보는 식이야. 모양이 딱 정해진 튜플 ([latitude, longitude], [year, month, day]) 에 써. 이 앞부분을 넘어가는 요소들은 items 가 맡고, items: false 로 아예 못 붙이게 막을 수도 있어.

크기 & 고유성

  • minItems, maxItems — 개수의 아래위 한계를 정해.
  • uniqueItems — boolean 이나 문자열, 숫자면 판정이 간단해. 객체는 속까지 다 비교해서 같은지 봐.
  • contains — 적어도 요소 하나가 이 sub-schema 에 맞아야 해.
원칙: 한 종류로만 채운 배열엔 items 를 쓰고, 튜플 모양 배열 ([latitude, longitude], [r, g, b, a]) 엔 prefixItems 를 써. prefixItems 로 충분한 자리에 oneOf 나 items 를 끌어오지 마. 읽기도 더 분명하고, 몇 번째 자리가 틀렸는지도 훨씬 잘 짚어주거든.

Code

동종 string 배열·json
{
  "type": "array",
  "items": { "type": "string" },
  "minItems": 1,
  "maxItems": 10,
  "uniqueItems": true
}
튜플 모양 (위치 인식)·json
{
  "type": "array",
  "prefixItems": [
    { "type": "number", "minimum": -90,  "maximum": 90 },
    { "type": "number", "minimum": -180, "maximum": 180 }
  ],
  "items": false,
  "minItems": 2,
  "maxItems": 2
}
contains — 적어도 한 요소 매칭 필수·json
{
  "type": "array",
  "items": { "type": "object" },
  "contains": {
    "type": "object",
    "properties": { "role": { "const": "admin" } },
    "required": ["role"]
  }
}

External links

Exercise

'쇼핑 카트' 객체 schema 를 써봐. items 는 상품 항목 배열이고 (각각 id, name, qty, price 를 가져), 최소 하나는 있어야 하고, 중복은 없어야 하고, 적어도 한 항목은 qty 가 1 보다 커야 해. 조건을 다 만족하는 카트 하나와 'qty > 1 인 게 하나는 있어야 한다' 만 어기는 카트 하나를 검증해봐. 그 마지막 조건을 실제로 잡아내는 건 contains 키워드야.

Progress

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

댓글 0

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

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