Akshay
Akshay

Reputation: 783

Generating validation code from JSON schema

Is there an existing python package that can help me generate code from a json schema?

For example if I have a JSON object like

{       
    "attribute": "obj.value",      
    "operator":  "greater than",      
    "value" : 235 
}

I want to be able to take this JSON and apply it as a rule over different objects to see which ones pass the rule.

So ideally I want to have something like

is_valid(obj,schema)

where

is_valid({"value":300},{"attribute":"value","operator":"greater than","value":235}) 

returns True

Upvotes: 0

Views: 827

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121158

The jsonschema project does exactly that, validate Python datastructures against a valid JSON schema:

from jsonschema import validate

validate(obj, schema)

This returns None when the schema is valid, and raises an exception when it is not. If you must have a boolean, use:

import jsonschema

def is_valid(obj, schema):
    try:
        jsonschema.validate(obj, schema)
    except jsonschema.ValidationError:
        return False
    else:
        return True

You do need to use valid JSON schema constraints. For integer values, limit the range if your value needs to adhere to boundaries, for example.

The dictionary {"value": 300} is a JSON object with a single key, where that single key is an integer with a lower boundary, so define that as a JSON schema:

schema = {
    "type": "object",
    "properties": {
        "value": {
            "type": "integer",
            "minimum": 235,
            "exclusiveMinimum": True
        }
    }
}

This schema validates your sample value:

>>> import jsonschema
>>> def is_valid(obj, schema):
...     try:
...         jsonschema.validate(obj, schema)
...     except jsonschema.ValidationError:
...         return False
...     else:
...         return True
...
>>> schema = {
...     "type": "object",
...     "properties": {
...         "value": {
...             "type": "integer",
...             "minimum": 235,
...             "exclusiveMinimum": True
...         }
...     }
... }
>>> is_valid({'value': 300}, schema)
True
>>> is_valid({'value': 1}, schema)
False

Read Understanding JSON Schema for a great tutorial on how to write such schemas.

Upvotes: 3

Related Questions