0

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

4
  • A quick google shows pypi.org/project/jsonschema, which does exactly what you want. Commented Aug 31, 2018 at 12:02
  • You can also use github.com/keleshev/schema to the same goal Commented Aug 31, 2018 at 12:09
  • @EPo: that's not a JSON Schema library. It has the same goal, but schemas are defined in Python, not in JSON. Commented Aug 31, 2018 at 12:12
  • 3
    However, your schema doesn't appear to be following the JSON schema format for numbers. Don't invent your own schema format, stick to a standard. Commented Aug 31, 2018 at 12:13

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

from what I understand jsonschema is only looking at types whereas I am looking at something more complicated like {"attribute":"value","operator":"not in","value":['a','b','c']} Correct me if I am wrong
@Akshay: if your schema is a valid JSON schema, then jsonschema.validate() works. The documentation includes examples like using "items" : {"enum" : [1, 2, 3]}, to restrict values, for example.
@Akshay: I added a sample schema for your sample object.
@Akshay: for your specific example of excluding a subset (not in a given list), you can use "not": {"enum": ["a", "b", "c"]}, so JSON schema almost certainly covers your use cases already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.