2013-12-23 42 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" 
}