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.

🌐
PyPI
pypi.org › project › json-schema-to-class
json-schema-to-class 0.2.4
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Discussions

A library for working with JSON Schemas; Create a class with attributes based on an external JSON Schema
This looks great. I look forward to eagerly deep diving. More on reddit.com
🌐 r/Python
4
6
December 11, 2019
multi agent - Generate a JSON Schema specification from Python classes - Stack Overflow
I am trying to develop multi-agent models in Python3. So my approach is to create basic classes and derive them to more concrete and specific ones. For instance, a class Bike inherits from Vehicle, itself inheriting from a basic Agent class. ... I want to offer a clear specification of my classes init parameters using JSON Schema ... More on stackoverflow.com
🌐 stackoverflow.com
From JSON to class implementation
The basic idea is to make a class that represents a device. Then use a routine to parse the json and instantiate objects using the class. When creating the object you pass the relevant data (json to dictionary) as a parameter. The class then has methods which are available based on the options in the data. The best way to walk through the objects is to create a list of objects. Then you can iterate over the list to call methods to talk to the devices in the real world via their protocols. look at this pseudo code. class MyDevice(): def __init__(self,data): self.data = data def Method(self,args): pass devices = [] for item in parsed_json: devices.append(MyDevice(item)) for device in devices: device.Method(args) # small edit to make it pythonic More on reddit.com
🌐 r/learnpython
9
0
June 20, 2023
Most secure json schema validation for node?
You want to validate the JSON schema itself or you want to validate a JSON against the schema ? If it's the later I would say ajv More on reddit.com
🌐 r/node
11
6
March 27, 2023
🌐
GitHub
github.com › microsoft › jschema-to-python
GitHub - microsoft/jschema-to-python: Generate source code for a set of Python classes from a JSON schema.
Generate Python classes from a JSON schema.
Starred by 38 users
Forked by 18 users
Languages   Python 100.0% | Python 100.0%
🌐
GitHub
github.com › cwacek › python-jsonschema-objects
GitHub - cwacek/python-jsonschema-objects: Automatic Python binding generation from JSON Schemas · GitHub
python-jsonschema-objects provides an automatic class-based binding to JSON Schemas for use in python.
Starred by 373 users
Forked by 90 users
Languages   Python
🌐
JSON Type Definition
jsontypedef.com › docs › python-codegen
Generating Python from JSON Typedef schemas
JSON Type Definition, aka RFC 8927, is an easy-to-learn, standardized way to define a schema for JSON data. You can use JSON Typedef to portably validate data across programming languages, create dummy data, generate code, and more. This article is about how you can use JSON Typedef to generate Python code from schemas.
🌐
PyPI
pypi.org › project › JSONSchema2PoPo2
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Find elsewhere
🌐
GitHub
github.com › FebruaryBreeze › json-schema-to-class
GitHub - FebruaryBreeze/json-schema-to-class: Convert JSON Schema into Python Class
Need Python 3.6+. ... # generate & highlight json-schema-to-class tests/test_schema.json --indent 2 | pygmentize # or generate to file json-schema-to-class tests/test_schema.json -o tests/schema_build.py # generate code with __repr__ method json-schema-to-class tests/test_schema.json --indent 2 --repr | pygmentize
Starred by 39 users
Forked by 5 users
Languages   Python 100.0% | Python 100.0%
🌐
Reddit
reddit.com › r/python › a library for working with json schemas; create a class with attributes based on an external json schema
r/Python on Reddit: A library for working with JSON Schemas; Create a class with attributes based on an external JSON Schema
December 11, 2019 -

This library is a bit like pydantic, dataclasses, or marshmallow, but takes a slightly different direction in that it tries to work within a schema system. Currently the only supported system is JSON Schema, but the infrastructure is there to do whatever, Postgres, Protocol Buffers, MsgPack, etc.

https://github.com/DeadWisdom/blazon

I'm using this for a web api project. I want to be able to represent a Swagger API, manipulated it, store it, load it, etc. It's pretty annoying to have to essentially recreate the schema in Python, so I've got something that does this now (from the tests):

import yaml
from blazon import Schematic, json

# Create a 'Schematic', works like a dataclass
class Swagger(Schematic):
    __schema__ = json.from_file(
        "swagger.yaml", name="Swagger")

s = Swagger()

# Not valid, because there are required fields
assert not s.validate()

# Valid once we have required fields
s.info = {"title": "Swagger Petstore", "version": "0.0.1"}
s.openapi = "3.0.0"
s.paths = []
assert s.validate()

# Load from external data
with open("petstore.yaml") as o:
    data = yaml.safe_load(o)

petstore = Swagger(**data)

assert petstore.info["title"] == "Swagger Petstore"
assert petstore.validate()

old_value = petstore.get_value()

# We can create sub-schemas, "Info" is referenced
# within the Swagger API class
class Info(Schematic):
    __schema__ = json.schemas["Info"]

# Now we can assign this schematic as it's own object
petstore.info = Info(
     title="Swagger Petstore", version="0.0.1")

# Still validates
assert petstore.validate()

# .info is now an Info instance
assert isinstance(petstore.info, Info)

# We access it with dots because info isn't a dict, 
# it's an Info Schematic
assert petstore.info.version == "0.0.1"

# Still the same 'value' as before
assert old_value == petstore.get_value()

# We can still assign it as a dict, shows up as Info object
petstore.info = {
    "title": "Swagger Petstore", "version": "0.0.1"}

assert old_value == petstore.get_value()
assert isinstance(petstore.info, Info)

The library takes an approach of "converting" incoming data, rather than merely validating it. A basic example, if the schema says that the value should be an string, but we see an int, we simply turn it into a string.

It has a lot of other features, which you can see in the docs, but I wanted to highlight this.

Looking for feedback on whatever you got, thanks.

🌐
Json2CSharp
json2csharp.com › code-converters › json-to-python
JSON to Python Classes Online Converter - Json2CSharp Toolkit
Convert any JSON string to Python classes online. - Json2CSharp.com is a free parser and converter that will help you generate Python classes from a JSON object.
🌐
TutorialsPoint
tutorialspoint.com › How-I-can-create-Python-class-from-JSON-object
How I can create Python class from JSON object?
June 16, 2020 - import python_jsonschema_objects as pjs builder = pjs.ObjectBuilder(schema) ns = builder.build_classes() Person = ns.ExampleSchema jack = Person(firstName="Jack", lastName="Sparrow") jack.lastName example_schema lastName=Sparrow age=None firstName=Jack
🌐
jsonschema
python-jsonschema.readthedocs.io › en › stable › creating
Creating or Extending Validator Classes - jsonschema 4.26.0 documentation
a mapping from names to callables, where each callable will validate the schema property with the given name. ... version – an identifier for the version that this validator class will validate. If provided, the returned validator class will have its __name__ set to include the version, and also will have jsonschema.validators.validates automatically called for the given version.
🌐
DEV Community
dev.to › stefanalfbo › python-json-schema-3o7n
Python JSON schema - DEV Community
May 9, 2024 - I have changed one thing in the ... permission_classes to permission.AllowAny, just for demo purposes. We can now extend our test and use the jsonschema library. In the example below is a test that is validating that the response from our API is fulfilling our contract (JSON schema) by using ...
🌐
Snyk
snyk.io › advisor › python packages › json-schema-codegen
json-schema-codegen - Python Package Health Analysis | Snyk
This python library consumes JSON-Schema and generates C++ or Python code. It generates structures to hold the values defined in the schema, restricting the values according to the schema. These requirements should be satisfied when pip3 installing json-schema-codegen. ... A C++ class is generated for each schema node according to the schema's type property.
Top answer
1 of 1
1

Pydantic can help you achieve this:

Example from the Pydantic documentation

from enum import Enum
from pydantic import BaseModel, Field


class FooBar(BaseModel):
    count: int
    size: float = None


class Gender(str, Enum):
    male = 'male'
    female = 'female'
    other = 'other'
    not_given = 'not_given'


class MainModel(BaseModel):
    """
    This is the description of the main model
    """

    foo_bar: FooBar = Field(...)
    gender: Gender = Field(None, alias='Gender')
    snap: int = Field(
        42,
        title='The Snap',
        description='this is the value of snap',
        gt=30,
        lt=50,
    )

    class Config:
        title = 'Main'


# this is equivalent to json.dumps(MainModel.schema(), indent=2):
print(MainModel.schema_json(indent=2))

Output:

# this is equivalent to json.dumps(MainModel.schema(), indent=2):
print(MainModel.schema_json(indent=2))

{
  "title": "Main",
  "description": "This is the description of the main model",
  "type": "object",
  "properties": {
    "foo_bar": {
      "$ref": "#/definitions/FooBar"
    },
    "Gender": {
      "$ref": "#/definitions/Gender"
    },
    "snap": {
      "title": "The Snap",
      "description": "this is the value of snap",
      "default": 42,
      "exclusiveMinimum": 30,
      "exclusiveMaximum": 50,
      "type": "integer"
    }
  },
  "required": [
    "foo_bar"
  ],
  "definitions": {
    "FooBar": {
      "title": "FooBar",
      "type": "object",
      "properties": {
        "count": {
          "title": "Count",
          "type": "integer"
        },
        "size": {
          "title": "Size",
          "type": "number"
        }
      },
      "required": [
        "count"
      ]
    },
    "Gender": {
      "title": "Gender",
      "description": "An enumeration.",
      "enum": [
        "male",
        "female",
        "other",
        "not_given"
      ],
      "type": "string"
    }
  }
}
🌐
Readthedocs
python-jsonschema-objects.readthedocs.io › en › latest › Introduction.html
What — Python JSONSchema Objects 0.0.18 documentation
python-jsonschema-objects provides an automatic class-based binding to JSON Schemas for use in python.
🌐
PyPI
pypi.org › project › json-schema-codegen
json-schema-codegen · PyPI
This example will create the file output_dir/example.py containing the Python3 class Example and nested classes as required. ... import example import json jsonText = '["an example string in an array"]' obj = example.Example(json.loads(jsonText)) print(json.dumps(obj, default=lambda x: x.Serializable())) ... Download the file for your platform. If you're not sure which to choose, learn more about installing packages. json-schema-codegen-0.6.3.tar.gz (17.5 kB view details)
      » pip install json-schema-codegen
    
Published   May 01, 2023
Version   0.6.3
🌐
CSDN
devpress.csdn.net › python › 630452907e66823466199c90.html
Convert a JSON schema to a python class_python_Mangs-Python
August 23, 2022 - >>> schema = { 'name': 'Country', 'properties': { 'name': {'type': 'string'}, 'abbreviation': {'type': 'string'}, }, 'additionalProperties': False, } ... 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.
🌐
PyPI
pypi.org › project › genson
genson · PyPI
-$ SCHEMA_URI, --schema-uri SCHEMA_URI The value of the '$schema' keyword (defaults to 'http://json-schema.org/schema#' or can be specified in a schema with the -s option). If 'NULL' is passed, the "$schema" keyword will not be included in the result. SchemaBuilder is the basic schema generator class.
      » pip install genson
    
Published   May 15, 2024
Version   1.3.0
🌐
GitHub
github.com › Peter554 › dc_schema
GitHub - Peter554/dc_schema: Generate JSON schema from python dataclasses
Create a regular python dataclass and pass it to get_schema. import dataclasses import datetime import json from dc_schema import get_schema @dataclasses.dataclass class Book: title: str published: bool = False @dataclasses.dataclass class Author: ...
Starred by 22 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%