programing

여러 속성 중 하나 이상이 필요한 JSON 스키마를 정의하는 방법

telebox 2023. 3. 23. 22:37
반응형

여러 속성 중 하나 이상이 필요한 JSON 스키마를 정의하는 방법

오브젝트에 가능한 많은 속성 중 적어도 하나를 필요로 하는 JSON 스키마(초안 4)를 정의할 수 있는지 알고 싶습니다.나는 이미 알고 있다allOf,anyOf그리고.oneOf내가 원하는 방식으로 어떻게 사용하는지 알 수가 없어.

다음으로 JSON의 예를 제시하겠습니다.

// Test Data 1 - Should pass
{

    "email": "hello@example.com",
    "name": "John Doe"
}
// Test Data 2 - Should pass
{
    "id": 1,
    "name": "Jane Doe"
}
// Test Data 3 - Should pass
{
    "id": 1,
    "email": "hello@example.com",
    "name": "John Smith"
}
// Test Data 4 - Should fail, invalid email
{
    "id": 1,
    "email": "thisIsNotAnEmail",
    "name": "John Smith"
}

// Test Data 5 - Should fail, missing one of required properties
{
    "name": "John Doe"
}

최소한 다음 중 하나를 요구했으면 합니다.id또는email(둘 다 수용 가능)하지만 형식에 따라 검증에 합격합니다.사용.oneOf양쪽(테스트 3)을 모두 지정하면 검증에 실패합니다.anyOf둘 중 하나가 유효하지 않은 경우에도 검증에 합격합니다(테스트 4).

스키마는 다음과 같습니다.

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "https://example.com",
    "properties": {
        "name": {
            "type": "string"
        }
    },
    "anyOf": [
        {
            "properties": {
                "email": {
                    "type": "string",
                    "format": "email"
                }
            }
        },
        {
            "properties": {
                "id": {
                    "type": "integer"
                }
            }
        }
    ]
}

사용 사례를 올바르게 검증하는 방법을 알려 주시겠습니까?

속성 집합 중 하나 이상을 요구하려면required일련의 내부anyOf옵션:

{
    "type": "object",
    "anyOf": [
        {"required": ["id"]},
        {"required": ["email"]}
        // any other properties, in a similar way
    ],
    "properties": {
        // Your actual property definitions here
    }
}

원하는 속성 중 하나가 존재하는 경우)"id","email")에 대응하는 옵션을 전달합니다.allOf.

사용할 수 있습니다.minProperties: number(그리고maxProperties: number(필요한 경우)그러면 스키마 정의가 짧아집니다.

{
     type: "object",
     minProperties: 1,
     properties: [/* your actual properties definitions */],
     additionalProperties: false
}

매뉴얼 링크: https://json-schema.org/understanding-json-schema/reference/object.html#size

언급URL : https://stackoverflow.com/questions/31839578/how-to-define-a-json-schema-that-requires-at-least-one-of-many-properties

반응형