简体   繁体   中英

AJV Multilevel/Nested JSON schema validation

Using the schema

{
  "type": "object",
  "required": [     
      "person", 
      "animal"
  ],
  "person": {
      "title": "person",
      "type": "object",
      "required": [
          "name"
      ],
      "properties": {
         "name": {
            "type": "string"
         }
      }
  },
  "animal": {
    "title": "animal",
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        }
    }
  }
}

This schema is valid when it is compared against this object

{
  "person": 0, 
  "animal": "dog"
}

I only want it to validate for the properties within person object (as it also has required properties). For example, only the following would be valid:

{
  "person": {
     "name": "myName"
  },
  "animal": "dog"
}

How can I ensure nested objects are validated in my schema using AJV?

In your schema, you need to put animal and person inside a properties object.

Currently, as those property keys are not within a properties object, they are classed as unkown keywords and ignored.

Otherwise, yeah, you have this correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM