如何在JSON Schema的引用Schema中添加属性额外约束及嵌套属性约束?
解决JSON Schema中为引用Schema添加嵌套必填属性的问题
你当前的问题核心是约束层级定位错误:
- 你期望
boundaries.properties.name为必填项,但原Schema直接给boundaries对象添加required: ["name"],导致校验工具认为name应该在boundaries顶层(和type、geometry同级),与你的实例结构不符。 - 对
geometry的约束也未正确嵌套在properties字段下,导致校验逻辑错位。
修正后的JSON Schema
{ "$schema": "https://json-schema.org/draft-07/schema#", "$id": "https://example.com/sample.schema.json", "type": "object", "properties": { "boundaries": { "description": "Boundaries", "allOf": [ { "$ref": "http://geojson.org/schema/Feature.json" }, { "type": "object", "properties": { "geometry": { "oneOf": [ { "$ref": "http://geojson.org/schema/MultiPolygon.json" }, { "$ref": "http://geojson.org/schema/Polygon.json" } ], "additionalProperties": false }, "properties": { "type": "object", "required": ["name"], "additionalProperties": true // 允许properties包含其他字段,按需改为false可严格限制仅name存在 } } } ] } } }
关键修正说明
- 嵌套属性的约束层级:
要约束boundaries下的子属性(如geometry、properties),必须在allOf的子Schema中通过properties字段嵌套定义。直接写顶层字段(如原Schema中的geometry)是无效的,因为非标准JSON Schema关键字会被当作普通属性处理,导致校验逻辑偏离预期。 - 必填字段的正确定位:
针对boundaries.properties.name的必填要求,需在properties.properties下定义required: ["name"],这样校验工具会正确识别到name是嵌套在boundaries.properties中的必填项。 - additionalProperties的灵活配置:
根据需求设置additionalProperties:如果允许boundaries.properties包含其他字段,设为true;如果需要严格仅保留name,则设为false并补充properties.name的具体类型定义。
实例验证
修正后的Schema可正确通过你提供的JSON实例校验,满足以下要求:
boundaries符合GeoJSON Feature的结构(通过$ref引用校验)boundaries.geometry被限制为Polygon或MultiPolygon类型boundaries.properties.name为必填项
内容的提问来源于stack exchange,提问作者afs76
相关产品推荐
相关产品推荐

