2017-07-12 5 views
0
var schema = { 
    "id": "test.json#", 
    "definitions": { 
    "body": { 
     "type": "object", 
     "properties": { 
     "name": {"type": "string"}, 
     "age": {"type": "integer"}, 
     } 
    }, 
    "request": { 
     "properties": { 
     "user": { 
      "$ref": "#/definitions/body" 
     } 
     } 
    } 
    }, 
    "typeA": { 
    "$ref": "#/definitions/request" 
    }, 
    "typeB": { 
    "allOf": [ 
     {"$ref": "#/definitions/request"}, 
     {"required": ["name"]} // Should require the name field in the user object. 
    ] 
    } 
} 

var Ajv = require('ajv') 
var ajv = Ajv({ 
    schemas: [schema] 
}) 

var data = { 
    user: { 
    "name": "tom", 
    "age": 1 
    } 
} 

var valid = ajv.validate({$ref: "test.json#/typeA"}, data) 
console.log('VALID', valid) // Returns true. 
var valid = ajv.validate({$ref: "test.json#/typeB"}, data) 
console.log('VALID', valid) // Returns false. 

Ich bin neu in JSON-Schemas. Ich möchte das Definitions-Anfrage-Schema in typeA und typeB wiederverwenden. TypB sollte das Namensfeld im Benutzerobjekt erfordern. Wie erreiche ich das? Ich weiß, warum meine obige Lösung nicht funktioniert. Erforderlich sollte etwas wie "user.name" sein.JSON-Schema - erfordert ein verschachteltes Feld

Vielen Dank für Ihre Hilfe.

Antwort

0

hier ist ein Beispiel dafür, wie verschachtelt Eigenschaften erfordern

{ 
    "$id": "add", 
    "properties": { 
     "label": {"type": "string"}, 
     "inputs": {"type": "array", "items": {"type": "string"}}, 
     "outputs": {"type": "array", "items": {"type": "string"}}, 
     "filter": {"type": "array", "items": {"type": "string"}}, 
     "componentConfig": { 
     "type": "object", 
     "properties": { 
      "component": {"type": "string"}, 
      "resource": {"type": "array", "items": {"type": "string"}}, 
      "centerAddress": {"type": "string"} 
     }, 
     "required": ["component", "resource"] 
     } 
    }, 
    "required": ["label", "inputs", "outputs", "filter"] 
    } 
Verwandte Themen