JSON Schema能否将InitialState值设为Instructions的必填属性?
JSON Schema 支持动态关联 InitialState 与 Instructions 必填项的功能
明确说:你的需求可以实现,但不能用你写的{"valueOf": "InitialState"}这种写法,需要借助JSON Schema Draft-07及以上版本支持的$data关键字来完成动态引用。
具体实现示例
以下是符合需求的完整JSON Schema结构,核心是通过$data将InitialState的取值动态设为Instructions的必填属性:
{ "type": "object", "properties": { "InitialState": { "type": "string", "minLength": 1 }, "Instructions": { "type": "object", "required": [ { "$data": "1/InitialState" } ], "additionalProperties": { // 这里定义Action对象的JSON Schema规则 "type": "object", "properties": { "Write": { "type": "string" }, "Move": { "type": "string", "enum": ["Left", "Right", "Stay"] }, "NextState": { "type": "string" } }, "required": ["Write", "Move", "NextState"] } } }, "required": ["InitialState", "Instructions"] }
关键规则说明
$data的路径逻辑:1/InitialState里的1代表当前Schema层级的父级(也就是整个code对象),InitialState就是要引用的属性名,这样就能自动将用户输入的InitialState值,设为Instructions必须包含的键名。- 兼容性要求:
$data关键字需要验证器支持JSON Schema Draft-07及以上版本,Ajv、JSON Schema Validator等主流工具都已支持。
验证效果
当用户填写的InitialState为"Step 1"时,Instructions必须包含"Step 1"属性;如果用户把InitialState改成"Start",Instructions就必须包含"Start"属性,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者Robotex
相关产品推荐
相关产品推荐

