Question

I have a remote schema "person.json", saved on another file.

{
    "id":"#person",
    "type":"object",
    "properties": {
        "name": {"type":"string"},
        "gender": {
            "type":"string",
            "enum":["m", "f"]
        },
        "age": {"type":"number"}
    },
    "additionalProperties": false
}

And I have a "man.json" schema, being this one my original schema.

{
    "id":"#man",
    "type":"object",
    "$ref":"person.json",
    "properties": {
        "beard":"boolean",
        "moustache":"boolean"
    },
    "required": ["name"],
    "additionalProperties": false
}

I want to use the properties: "name, gender, etc" from person.json at the same level as the properties: "beard, moustache" from man.json.

Example for validation

{
    name: 'John',
    gender: 'm',
    age: 29,
    beard: false,
    moustache: true
}

I want to validate the previously shown example, as you see, with all the properties at the same level (not nested).

Is this possible? If yes, how? Thank you very much.

João

Was it helpful?

Solution

You want to use the allOf keyword, combined with $ref:

{
    "id": "/schemas/man.json",
    "allOf": [{"$ref": "person.json"}],
    ...
}

(Note: This is v4. In v3, the same thing was called extends.)

In plain English, it says "Every instance following Man schema must also follow the Person schema".

The bigger issue is in fact your use of additionalPropeties. Since person.json bans additional properties, any instance with a "beard" property is actually not a valid Person. If you're going to be extending Person, I advise you remove the constraint banning additional properties.

(Note: this behaviour is the subject of some conflict in the JSON Schema community, but this is what's in the specs.)

OTHER TIPS

I'm guessing a piece of data cannot satisfy two schemas at once, so you'll need to create a third schema which combines them and validate against that.

var personSchema = JSON.parse(person_json);
var manSchema = JSON.parse(man_json)

for (var personProp in personSchema.properties) {
    manSchema.properties[personProp] = personSchema.properties[personProp];
}

var manPersonSchema = JSON.stringify(manSchema);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top