JSON 데이터는 Key, Value 로 이루어진 데이터 쌍이다.
그렇다면 JSON 데이터가 정해진 규칙에 따라서 구성되어 있는지 유효성 검사는 어떻게 할 수 있을까?
JSON Schema 가 그 대답이 될 수 있겠다.
JSON Schema 는 JSON 형태의 데이터가 정해진 규약에 맞게 구성되어 있는지 검사하는 규칙이다.
{
"type": "object",
"properties": {
"customerName": {
"type": "string"
},
"creditCardNumber": {
"type": "string"
},
"billingAddress": {
"type": "string"
}
},
"dependencies": {
"creditCardNumber": ["billingAddress"]
}
}
위와 같이 dependencies 를 정의해 놓은 경우 아래와 같은 경우는 허용되지 않는다 {
"customerName": "kimtaeng",
"creditCardNumber": "12341234"
}
- minProperties, maxProperties: 객체가 갖고 있는 속성의 최소/최대 개수
{
"type": "object",
"minProperties": 2,
"maxProperties": 3
}
{
"type": "array",
"items": [
{
"type": "integer",
},
{
"type": "string",
"format": "date",
},
{
"type": "string"
}
],
"additionalItems": false
"uniqueItems": true
"minItems": 5,
"maxItems": 10
}
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"title": {
"type": "string"
},
"type": {
"type": "integer"
}
},
"required": ["id", "title"]
}
{"type": "string", "pattern": "(younghwan/cha)\\.com"
{"type": "number", "multipleOf": 5}
{"type": "string", "format": "date"}
{"type": "string", "contentEncoding": "base64", "contentMediaType": "application/json"}
{
"title": "어떤어떤 스키마",
"description": "이 스키마는 이렇게 저렇게 하는 용도입니다.",
"example": ["mad", "play"],
"$comment": "음... 그냥 남겨 봅니다 :)",
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"$comment": "음, 이게 과연 좋은 건지 모르겠어요 :(",
"type": "string",
"pattern": "^a"
}
}
}
https://madplay.github.io/post/json-schema-validation-examples
https://madplay.github.io/post/multiple-and-conditional-json-schemas-validation-examples