So far the closest thing I've been able to find is warlock, which advertises this workflow:

Build your schema

>>> schema = {
    'name': 'Country',
    'properties': {
        'name': {'type': 'string'},
        'abbreviation': {'type': 'string'},
    },
    'additionalProperties': False,
}

Create a model

>>> import warlock
>>> Country = warlock.model_factory(schema)

Create an object using your model

>>> sweden = Country(name='Sweden', abbreviation='SE')

However, it's not quite that easy. The objects that Warlock produces lack much in the way of introspectible goodies. And if it supports nested dicts at initialization, I was unable to figure out how to make them work.

To give a little background, the problem that I was working on was how to take Chrome's JSONSchema API and produce a tree of request generators and response handlers. Warlock doesn't seem too far off the mark, the only downside is that meta-classes in Python can't really be turned into 'code'.

Other useful modules to look for:

  • jsonschema - (which Warlock is built on top of)
  • valideer - similar to jsonschema but with a worse name.
  • bunch - An interesting structure builder thats half-way between a dotdict and construct

If you end up finding a good one-stop solution for this please follow up your question - I'd love to find one. I poured through github, pypi, googlecode, sourceforge, etc.. And just couldn't find anything really sexy.

For lack of any pre-made solutions, I'll probably cobble together something with Warlock myself. So if I beat you to it, I'll update my answer. :p

Answer from synthesizerpatel on Stack Overflow
Top answer
1 of 5
39

So far the closest thing I've been able to find is warlock, which advertises this workflow:

Build your schema

>>> schema = {
    'name': 'Country',
    'properties': {
        'name': {'type': 'string'},
        'abbreviation': {'type': 'string'},
    },
    'additionalProperties': False,
}

Create a model

>>> import warlock
>>> Country = warlock.model_factory(schema)

Create an object using your model

>>> sweden = Country(name='Sweden', abbreviation='SE')

However, it's not quite that easy. The objects that Warlock produces lack much in the way of introspectible goodies. And if it supports nested dicts at initialization, I was unable to figure out how to make them work.

To give a little background, the problem that I was working on was how to take Chrome's JSONSchema API and produce a tree of request generators and response handlers. Warlock doesn't seem too far off the mark, the only downside is that meta-classes in Python can't really be turned into 'code'.

Other useful modules to look for:

  • jsonschema - (which Warlock is built on top of)
  • valideer - similar to jsonschema but with a worse name.
  • bunch - An interesting structure builder thats half-way between a dotdict and construct

If you end up finding a good one-stop solution for this please follow up your question - I'd love to find one. I poured through github, pypi, googlecode, sourceforge, etc.. And just couldn't find anything really sexy.

For lack of any pre-made solutions, I'll probably cobble together something with Warlock myself. So if I beat you to it, I'll update my answer. :p

2 of 5
28

python-jsonschema-objects is an alternative to warlock, build on top of jsonschema

python-jsonschema-objects provides an automatic class-based binding to JSON schemas for use in python.

Usage:

Sample Json Schema

schema = '''{
    "title": "Example Schema",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        },
        "dogs": {
            "type": "array",
            "items": {"type": "string"},
            "maxItems": 4
        },
        "gender": {
            "type": "string",
            "enum": ["male", "female"]
        },
        "deceased": {
            "enum": ["yes", "no", 1, 0, "true", "false"]
            }
    },
    "required": ["firstName", "lastName"]
} '''

Converting the schema object to class

 import python_jsonschema_objects as pjs
 import json
 schema = json.loads(schema)   
 builder = pjs.ObjectBuilder(schema)   
 ns = builder.build_classes()   
 Person = ns.ExampleSchema   
 james = Person(firstName="James", lastName="Bond")   
 james.lastName  
  u'Bond'  james      
 example_schema lastName=Bond age=None firstName=James  

Validation :

james.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0

But problem is , it is still using draft4validation while jsonschema has moved over draft4validation , i filed an issue on the repo regarding this . Unless you are using old version of jsonschema , the above package will work as shown.

🌐
Medium
medium.com › grammofy › handling-complex-json-schemas-in-python-9eacc04a60cf
Handling complex JSON Schemas in Python | by Paul Götze | Grammofy | Medium
August 21, 2020 - In a previous post we looked at how to test your Python API app with JSON Schema. In case you have to deal with complex and nested JSON data, schema definitions can get long and confusing. However, there are ways to clean up and reuse your schemas by using references.
🌐
GitHub
github.com › jacksmith15 › statham-schema
GitHub - jacksmith15/statham-schema: Statham is a Python Model Parsing Library for JSON Schema.
`--input path/to/document.json#/definitions/schema` Optional arguments: --output OUTPUT Output directory or file in which to write the output. If the provided path is a directory, the command will derive the name from the input argument. If not passed, the command will write to stdout. -h, --help Display this help message and exit. This project requires Python 3.6+ and may be installed using pip:
Starred by 38 users
Forked by 9 users
Languages   Python 98.4% | Shell 1.1% | Makefile 0.5% | Python 98.4% | Shell 1.1% | Makefile 0.5%
🌐
GitHub
github.com › cwacek › python-jsonschema-objects
GitHub - cwacek/python-jsonschema-objects: Automatic Python binding generation from JSON Schemas · GitHub
These classes can seamlessly encode back and forth to JSON valid according to the schema. Literal values are wrapped when constructed to support validation and other schema-related operations. However, you can still use them just as you would other literals. >>> import python_jsonschema_objects as pjs >>> builder = pjs.ObjectBuilder(examples['Example Schema']) >>> ns = builder.build_classes() >>> Person = ns.ExampleSchema >>> james = Person(firstName="James", lastName="Bond") >>> str(james.lastName) 'Bond' >>> james.lastName += "ing" >>> str(james.lastName) 'Bonding' >>> james.age = 4 >>> james.age - 1 3 >>> 3 + james.age 7 >>> james.lastName / 4 Traceback (most recent call last): ...
Starred by 373 users
Forked by 90 users
Languages   Python
🌐
jsonschema
python-jsonschema.readthedocs.io
jsonschema 4.26.0 documentation
Be aware that the mere presence of these dependencies – or even the specification of format checks in a schema – do not activate format checks (as per the specification). Please read the format validation documentation for further details. If you have nox installed (perhaps via pipx install nox or your package manager), running nox in the directory of your source checkout will run jsonschema’s test suite on all of the versions of Python jsonschema supports.
🌐
Windmill
windmill.dev › json schema and parsing
JSON schema and parsing | Windmill
Scripts in Windmill have input ... of a script corresponds to a field in the JSON Schema. This one-to-one correspondence ensures that the name of the argument becomes the name of the property, and most primitive types in Python and TypeScript have a corresponding primitive ...
🌐
PyPI
pypi.org › project › jsonschema
jsonschema - JSON Schema validation for Python
>>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema) >>> validate( ... instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema, ... ) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValidationError: 'Invalid' is not of type 'number' It can also be used from the command line by installing check-jsonschema.
      » pip install jsonschema
    
Published   Jan 07, 2026
Version   4.26.0
🌐
Built In
builtin.com › software-engineering-perspectives › python-json-schema
How to Use JSON Schema to Validate JSON Documents in Python | Built In
If you want to define the schema for a tuple field, you would need to have some understanding of JSON Schema drafts, which is a bit more advanced. A draft is a standard or specification for the JSON Schema and defines how the schema should be parsed by a validator.
Find elsewhere
🌐
GitHub
github.com › python-jsonschema
Python + JSON Schema · GitHub
JSON Schema implementation and surrounding tooling for Python - Python + JSON Schema
🌐
DEV Community
dev.to › stefanalfbo › python-json-schema-3o7n
Python JSON schema - DEV Community
May 9, 2024 - Finally the last property, groups, is of the type array and the items defines how each element in that array should look like. However, in this case we don't really know the type, so we use {} to indicate any type. As you can see it's pretty straightforward to define a json-schema for JSON data.
🌐
Horejsek
horejsek.github.io › python-fastjsonschema
Fast JSON schema for Python — fastjsonschema documentation
Generates validation code for validating JSON schema passed in definition. Example: import fastjsonschema code = fastjsonschema.compile_to_code({'type': 'string'}) with open('your_file.py', 'w') as f: f.write(code) ... echo "{'type': 'string'}" | python3 -m fastjsonschema > your_file.py python3 -m fastjsonschema "{'type': 'string'}" > your_file.py
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
TypeAdapter.json_schema returns a jsonable dict of an adapted type's schema. ... These methods are not to be confused with BaseModel.model_dump_json and TypeAdapter.dump_json, which serialize instances of the model or adapted type, respectively.
Top answer
1 of 2
2

The following code may help. It supports nested dict as well.

import json


def valid_type(type_name, obj):
    if type_name == "number":
        return isinstance(obj, int) or isinstance(obj, float)

    if type_name == "int":
        return isinstance(obj, int)

    if type_name == "float":
        return isinstance(obj, float)

    if type_name == "string":
        return isinstance(obj, str)


def validate_and_extract(request, schema):
    ''' Validate request (dict) against the schema (dict).

        Validation is limited to naming and type information.
        No check is done to ensure all elements in schema
        are present in the request. This could be enhanced by
        specifying mandatory/optional/conditional information
        within the schema and subsequently checking for that.
    '''
    out = {}

    for k, v in request.items():
        if k not in schema['properties'].keys():
            print("Key '{}' not in schema ... skipping.".format(k))
            continue

        if schema['properties'][k]['type'] == 'object':
            v = validate_and_extract(v, schema['properties'][k])

        elif not valid_type(schema['properties'][k]['type'], v):
            print("Wrong type for '{}' ... skipping.".format(k))
            continue

        out[schema['properties'][k]['mapped_name']] = v

    return out


# Sample Data 1
schema1 = {
    "type" : "object",
    "properties" : {
        "price" : {
            "type" : "number",
            "mapped_name": "product_price"
        },
        "name" : {
            "type" : "string",
            "mapped_name": "product_name"

        },
        "added_at":{
            "type" : "int",
            "mapped_name": "timestamp"

        },
    },
}
request1 = {
    "name" : "Eggs",
    "price" : 34.99,
    'added_at': 1234567
}

# Sample Data 2: containing nested dict
schema2 = {
    "type" : "object",
    "properties" : {
        "price" : {
            "type" : "number",
            "mapped_name": "product_price"
        },
        "name" : {
            "type" : "string",
            "mapped_name": "product_name"
        },
        "added_at":{
            "type" : "int",
            "mapped_name": "timestamp"
        },
        "discount":{
            "type" : "object",
            "mapped_name": "offer",
            "properties" : {
                "percent": {
                    "type" : "int",
                    "mapped_name": "percentage"
                },
                "last_date": {
                    "type" : "string",
                    "mapped_name": "end_date"
                },
            }
        },
    },
}
request2 = {
    "name" : "Eggs",
    "price" : 34.99,
    'added_at': 1234567,
    'discount' : {
        'percent' : 40,
        'last_date' : '2016-09-25'
    }
}


params = validate_and_extract(request1, schema1)
print(params)

params = validate_and_extract(request2, schema2)
print(params)

Output from running this:

{'timestamp': 1234567, 'product_name': 'Eggs', 'product_price': 34.99}
{'offer': {'percentage': 40, 'end_date': '2016-09-25'}, 'timestamp': 1234567, 'product_name': 'Eggs', 'product_price': 34.99}
2 of 2
1

See http://json-schema.org

This doesn't look like a Python question.

🌐
CodeRivers
coderivers.org › blog › json-parse-in-python
JSON Parsing in Python: A Comprehensive Guide - CodeRivers
April 24, 2025 - Python has a built-in json module that provides functions for working with JSON data. To use it, you first need to import the module: ... The json.loads() function is used to parse a JSON string and convert it into a Python data structure.
🌐
PyPI
pypi.org › project › genson
genson · PyPI
November 19, 2025 - -d DELIM, --delimiter DELIM Set a delimiter. Use this option if the input files contain multiple JSON objects/schemas. You can pass any string. A few cases ('newline', 'tab', 'space') will get converted to a whitespace character. If this option is omitted, the parser will try to auto-detect boundaries.
      » pip install genson
    
Published   May 15, 2024
Version   1.3.0
🌐
freeCodeCamp
freecodecamp.org › news › how-to-parse-json-in-python-with-examples
How to Parse JSON in Python – A Complete Guide With Examples
October 29, 2025 - This guide covers practical JSON parsing techniques you can use in your projects right away. Let’s get started! ... JSON represents data using a simple syntax with six data types: objects (key-value pairs), arrays, strings, numbers, Booleans, and null. When Python parses JSON, these types map directly to Python equivalents:
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to use json schema to validate json documents in python
How to Use JSON Schema to Validate JSON Documents in Python | Towards Data Science
March 5, 2025 - If you want to define the schema for a tuple field, you would need to have some knowledge of a draft in JSON schema, which is a bit more advanced. A draft is a standard or specification for the JSON schema and defines how the schema should be parsed by a validator.
🌐
PYnative
pynative.com › home › python › json › validate json data using python
Validate JSON data using Python
May 14, 2021 - First, install jsonschema using pip command. pip install jsonschema · Define Schema: Describe what kind of JSON you expect · Convert JSON to Python Object using json.load or json.loads methods.
🌐
Python.org
discuss.python.org › python help
How should/can I convert loaded JSON data into Python objects? - Python Help - Discussions on Python.org
October 25, 2022 - I have JSON input like this: { "accountID": "001-002-003-004", "accountClass": "Primary", "id": "1-2", "openTime": "2019-12-21T02:12:17.122Z", "priceDifference": "0.12345", } I would like to deserialise it in…
🌐
GitHub
github.com › python-jsonschema › jsonschema
GitHub - python-jsonschema/jsonschema: An implementation of the JSON Schema specification for Python · GitHub
>>> from jsonschema import validate >>> # A sample schema, like what we'd get from json.load() >>> schema = { ... "type" : "object", ... "properties" : { ... "price" : {"type" : "number"}, ... "name" : {"type" : "string"}, ... }, ... } >>> # ...
Starred by 4.9K users
Forked by 610 users
Languages   Python 99.8% | TypeScript 0.2%