简体   繁体   中英

Python jsonschema validation

In Python, I need to validate complex json data structure like this:

datainstances = {"apache1" :{"user":1,"dirname":"apache1dir","blah":42},"apache2" :{"user":"apache2","dirname":"apache2dir"},"apache3" :{"user1":"apache2","dirname":"apache2dir"}}

So I use jsonschema validate function against this schema

schemainstances = { 

                    "definitions" :{
                      "instance":{
                        "type":"object",
                        "properties": {
                          "user": {"type":"string"},
                          "dirname": {"type":"string"},
                          "blah": {"type":"string"}

                        },
                        "required" : ["user","blah"]
                      }
                  },
                  "type":"object",
                  "patternProperties": {
                    "^[a-z]+$": {"$ref": "#/definitions/instance"}  
                  }

}

My purpose is that it should not validate this json structure as :

  1. user properties of apache1 must be a string a
  2. blah properties of apache1 must be a string too

Did I do it wrong? Is something that I did not see

EDIT Code

import json
from jsonschema import validate
schemainstances = { 

                    "definitions" :{
                      "instance":{
                        "type":"object",
                        "properties":{
                          "user": {"type":"string"},
                          "dirname": {"type":"string"},
                          "blah": {"type":"string"}

                        },
                        "required" : ["user","blah"]
                      }
                  },
                  "type":"object",
                  "patternProperties":{
                    "^[a-z]+$": {"$ref": "#/definitions/instance"}  
                  }

}



datainstances = {"apache1" :{"user":1,"dirname":"apache1dir","blah":42},"apache2" :{"user":"apache2","dirname":"apache2dir"},"apache3" :{"user1":"apache2","dirname":"apache2dir"}}


retour = validate(datainstances,schemainstances)

print(retour)

Your patternProperties entry has regex "^[az]+$". The key is "apache1". This key does not match your regex because it contains a digit. Because patternProperties doesn't match, there are no constraints enforced on your data. Everything will validate. Perhaps you want "^[a-z0-9]+$" or "^[az]+[0-9]$" or "^[az]".

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