Python package: jsonschema for checking schemas and custom error messages

Given this scheme:

{
    "type": "object",
    "properties": {
        "account": {
            "type": "object",
            "required": ["id"],
            "properties": {
                "id": {"type": "number"}
            }
        },
        "name": {"type": "string"},
        "trigger": {
            "type": "object",
            "required": ["type"],
            "properties": {
                "type": {"type": "string"}
            }
        },
        "content": {
            "type": "object",
            "properties": {
                "emails": {
                    "type": "array",
                    "minItems": 1,
                    "items": {
                        "type": "object",
                        "required": ["fromEmail","subject"],
                        "properties": {
                            "fromEmail": {"type": "string", "format": "email"},
                            "subject": {"type": "string"}
                        }
                    }
                }
            }
        }
    }
}

I am trying to use jsonschema.Draft4ValidatorPOSTed JSON to validate the object, but I am having some problems trying to come up with better humanoid messages from the returned errors.

Here is how I check:

from jsonschema import Draft4Validator

v = Draft4Validator(self.schema)
errors = sorted(v.iter_errors(autoresponder_workflow), key=lambda e: e.path)

if errors:
    print(', '.join(
        '%s %s %s' % (error.path.popleft(), error.path.pop(), error.message) for error in errors
    ))

The error message looks like this:

content emails [] is too short, trigger type None is not of type u'string'

I am trying to create an error message that looks a little bigger. Please add at least one email to the workflow. "Please make sure all your letters contain subject lines," etc.

+4
source share
2 answers

ValidationError , ValidationError. :

: : (, )

+1

scrub validate. None , jsonschema None. : jsonschema.exceptions.ValidationError: None is not of type u'string'.

def scrub(x):
    ret = copy.deepcopy(x)
    if isinstance(x, dict):
        for k, v in ret.items():
            ret[k] = scrub(v)
    if isinstance(x, (list, tuple)):
        for k, v in enumerate(ret):
            ret[k] = scrub(v)
    if x is None:
        ret = ''
    return ret
0

All Articles