LoginSignup
9
7

More than 5 years have passed since last update.

PythonのDSLでJSON Schemaを書く

Posted at

JSON SchemaというJSONのスキーマをJSONで定義するものがある。が,JSON Schemaを手でちまちま書いていると面倒なので作成のためのツールがある。そのなかでPythonでJSON SchemaのDSLを作成したjslというパッケージについて簡単な説明をする。

サンプルとして以下のようなJSON Schemaを使う。

{
    "title": "Example Schema",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}

これをjslを使って定義すると次のようになる。

import jsl

class Example(jsl.Document):
    class Options(object):
        title = "Example Schema"
    firstName = jsl.StringField(required=True)
    lastName = jsl.StringField(required=True)
    age = jsl.IntField(description="Age in years", minimum=0)

これを出力したい場合はクラスメソッドのget_schemaを使う。

import json

print(json.dumps(Example.get_schema(ordered=True), indent=4))

参考

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7