Convert a JSON schema to a python class
Is there a python library for converting a JSON schema to a python class definition, similar to jsonschema2pojo -- https://github.com/joelittlejohn/jsonschema2pojo -- for Java?
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
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.
저는 json 스키마에서 코드 클래스를 생성하기 위해 이 작은 프로젝트를 만들었습니다.비록 python을 다루더라도 비즈니스 프로젝트에서 작업할 때 유용하다고 생각합니다.
pip install jsonschema2popo
다음 명령을 실행하면 json-module 정의 클래스를 포함하는 python 모듈이 생성됩니다(jinja2 템플릿 사용).
jsonschema2popo -o /path/to/output_file.py /path/to/json_schema.json
자세한 것은, https://github.com/frx08/jsonschema2popo 를 참조해 주세요.
언급URL : https://stackoverflow.com/questions/12465588/convert-a-json-schema-to-a-python-class
'programing' 카테고리의 다른 글
| [ spring _ web ]라는 이름의 fragment가 여러 개 발견되었습니다.이것은 상대적인 주문에서는 합법적이지 않습니다. (0) | 2023.03.21 |
|---|---|
| 같은 페이지에서 Greasemonkey 스크립트를 여러 번 실행하시겠습니까? (0) | 2023.03.21 |
| 닫힘 이벤트 후 각도 의 모달 (0) | 2023.03.21 |
| JavaScript:AJAX 요청 탐지 (0) | 2023.03.21 |
| Wordpress 관리 막대가 사이트 프런트엔드에 표시되지 않음 (0) | 2023.03.21 |