JSON Schema多条件校验求助:'My Self'旅行者姓名需匹配投保人
Solution for Your JSON Schema Validation Requirements
Let's fix your JSON Schema to properly enforce the two validation rules you need. Your original schema covers basic structure, but we need to add targeted checks for the traveller array conditions.
Key Gaps in Your Original Schema
- It doesn’t ensure at least one traveller has
relationship: "My Self" - It incorrectly links all travellers’
fullNameto the policyHolder’s, which isn’t your requirement (only the "My Self" traveller needs this match)
Corrected JSON Schema
{ "type": "object", "required": ["policyHolder", "traveller"], "properties": { "policyHolder": { "type": "object", "required": ["fullName"], "properties": { "fullName": { "type": "string" } } }, "traveller": { "type": "array", "minItems": 1, // Rule 1: Guarantee at least one traveller has relationship "My Self" "contains": { "properties": { "relationship": { "const": "My Self" } }, "required": ["relationship"] }, "items": { "type": "object", "properties": { "fullName": { "type": "string" }, "relationship": { "type": "string" } }, "required": ["fullName", "relationship"], // Rule 2: Match fullName to policyHolder if relationship is "My Self" "if": { "properties": { "relationship": { "const": "My Self" } }, "required": ["relationship"] }, "then": { "properties": { "fullName": { "$data": "/policyHolder/fullName" } } } } } } }
Breakdown of the Changes
Rule 1 Enforcement:
- We added the
containskeyword to thetravellerarray. This checks that at least one element in the array meets the nested condition (whererelationshipis exactly "My Self").
- We added the
Rule 2 Enforcement:
- Inside the
itemsschema for travellers, we used anif/thenblock. - The
ifclause triggers when a traveller’srelationshipis "My Self". - The
thenclause uses the$datakeyword to reference thepolicyHolder.fullNamevalue, ensuring the traveller’sfullNamematches exactly. Note:$dataworks in JSON Schema draft-06 and later—make sure your validator supports this version.
- Inside the
Test Scenarios
Your provided JSON instance:
{ "policyHolder": { "fullName": "A" }, "traveller": [ { "fullName": "B", "relationship": "Spouse" }, { "fullName": "A", "relationship": "My Self" } ] }
- This will pass validation: it includes a "My Self" traveller, and their fullName matches the policyHolder’s.
Invalid Cases That Fail
- No "My Self" traveller: Violates Rule 1
- "My Self" traveller has fullName "C" (when policyHolder is "A"): Violates Rule 2
- Missing
policyHolderortraveller: Fails top-level required checks
内容的提问来源于stack exchange,提问作者rajya vardhan
相关产品推荐
相关产品推荐

