2013-12-23 41 views
9

我有一个JSON模式JSON模式 - 递归模式定义

{ 
    'description': 'TPNode', 
    'type': 'object', 
    'id': 'tp_node', 
    'properties': { 
     'selector': { 
      'type': 'string', 
      'required': true 
     }, 
     'attributes': { 
      'type': 'array', 
      'items': { 
       'name': 'string', 
       'value': 'string' 
      } 
     }, 
     'children': { 
      'type': 'array', 
      'items': { 
       'type': 'object', 
       '$ref': '#' 
      } 
     }, 
     'events': { 
      'type': 'array', 
      'items': { 
       'type': 'object', 
       'properties': { 
        'type': { 
         'type': 'string' 
        }, 
        'handler': { 
         'type': 'object' 
        }, 
        'dependencies': { 
         'type': 'array', 
         'items': { 
          'type': 'string' 
         } 
        } 
       } 
      } 
     } 
    } 
} 

我试图在孩子财产表达的是,它是对象的数组用完全相同的架构。这是描述它的正确方法吗?

+0

你为什么要使用V3的语法? '“required”'是v4中的一个数组。 – cloudfeet

+0

你是对的。不过,我正在通过JSON.NET验证模式,因为我发现它不支持v4语法。 – William

回答

11

使用需要引用

'$ref': 'tp_node' 

看到这里的架构的idhttp://json-schema.org/latest/json-schema-core.html#anchor30

+3

问题中提出的解决方案(使用'“$ ref”:“#”')实际上更好,因为即使模式被移动/重命名,它也可以工作。用你的解决方案,如果你重新命名模式,那么你需要改变一堆引用,而这些引用可能是内部的。 – cloudfeet

+0

这种解决方案是可取的,应该是公认的解决方案;在模式发生变化的情况下,它会干净而明显地中断,相对于使用'“$ ref”:“#”'的更普遍的变化可能更难以诊断错误。 –

14

是的,你的模式会工作。 "$ref": "#"指向模式文档的根目录。

然而,"type": "object"是没用的:

{ 
    'type': 'object', 
    '$ref': '#' 
} 

如果$ref存在,那么所有其他的关键字会被忽略。从#/properties/children/items模式中删除type会更好。

3

使用定义和$ ref。

您可以将以下模式复制并粘贴到此online json/schema editor并检查结果。

编辑截图:

editor screenshot

架构代码:

{ 
    "definitions": { 
     "TPNode": { 
      "title": "TPNode", 
      "description": "TPNode", 
      "type": "object", 
      "properties": { 
       "selector": { 
        "type": "string", 
        "required": true 
       }, 
       "attributes": { 
        "type": "array", 
        "items": { 
         "title": "Attribute", 
         "type": "object", 
         "properties": { 
          "name": { 
           "type": "string" 
          }, 
          "value": { 
           "type": "string" 
          } 
         } 
        } 
       }, 
       "children": { 
        "type": "array", 
        "items": { 
         "$ref": "#/definitions/TPNode" 
        } 
       }, 
       "events": { 
        "type": "array", 
        "items": { 
         "title": "Event", 
         "type": "object", 
         "properties": { 
          "type": { 
           "type": "string" 
          }, 
          "handler": { 
           "type": "object" 
          }, 
          "dependencies": { 
           "type": "array", 
           "items": { 
            "type": "string" 
           } 
          } 
         } 
        } 
       } 
      } 
     } 
    }, 
    "$ref": "#/definitions/TPNode" 
}