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 OverflowSo 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
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.
A library for working with JSON Schemas; Create a class with attributes based on an external JSON Schema
multi agent - Generate a JSON Schema specification from Python classes - Stack Overflow
From JSON to class implementation
Most secure json schema validation for node?
Videos
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.
» pip install json-schema-codegen
» pip install genson