项目作者: jacopodl

项目描述 :
jsonschema to python class converter
高级语言: Python
项目地址: git://github.com/jacopodl/JSchema2py.git
创建时间: 2018-07-11T12:03:09Z
项目社区:https://github.com/jacopodl/JSchema2py

开源协议:MIT License

下载


JSchema2py

JSchema2py is able to generate python classes starting from JSONSchema and provides the automatic support for types
and constraints checking.

Installation

The package can be installed through pip:

  1. $ pip install jschema2py

or downloaded from GitHub.

Examples

For example, given the following schema:

  1. {
  2. "title": "UserInfo",
  3. "type": "object",
  4. "properties": {
  5. "name": {
  6. "type": "string",
  7. "pattern": "^[^a-z0-9]"
  8. },
  9. "userName": {
  10. "type": "string"
  11. },
  12. "age": {
  13. "type": "integer",
  14. "minimum": 0,
  15. "maximum": 100
  16. }
  17. }
  18. }

jschema2py can easily convert it into python class in this way (Assume here that the schema is stored into variable
called schema):

  1. from jschema2py import build_class
  2. UserInfo = build_class(schema)
  3. user = UserInfo()
  4. user.name = "Jacopo"
  5. user.userName = "JDL"
  6. user.age = 24
  7. print(user)

validation will be performed on the object manipulation:

  1. user.name = "jacopo" # raise ConstraintError (pattern: ^[^a-z0-9])
  2. user.age = "24" # raise TypeError

The object can be serialized into a JSON document:

  1. jsdoc = str(user)

Accessing generated classes

If one of the property of the schema refers to another object, you can access the class that represents the referred
object by using method get_class:

  1. {
  2. "title": "Nested",
  3. "type": "object",
  4. "properties": {
  5. "inner": {
  6. "title": "Inner",
  7. "type": "object",
  8. "properties": {
  9. "string": {
  10. "type": "string",
  11. "default": "I'm inner!"
  12. }
  13. }
  14. }
  15. }
  16. }
  1. from jschema2py import build_class
  2. Nested = build_class(schema)
  3. nested = Nested()
  4. nested.inner = nested.get_class("inner")() # Gets the class associated with the property "inner"
  5. print(nested.inner.string)