Python で、JSON Schema Validation

API の body リクエストの内容を jsonschema ライブラリを使って、簡単にチェックしよう

インストール

$ pip install jsonschema

実装するもの

{
  "id": 1,
  "name": "A green door",
  "price": 12.5,
  "checked": false,
  "tags": [
    "home",
    "green"
  ]
}
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "properties": {
    "checked": {
      "type": "boolean"
    },
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "price": {
      "type": "number"
    },
    "tags": {
      "items": {
        "type": "string"
      },
      "type": "array"
    }
  },
  "required": [
    "id",
    "name"
  ],
  "type": "object"
}

バリデーションチェック

import jsonschema
schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "properties": {
    "checked": {
      "type": "boolean"
    },
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "price": {
      "type": "number"
    },
    "tags": {
      "items": {
        "type": "string"
      },
      "type": "array"
    }
  },
  "required": [
    "id",
    "name"
  ],
  "type": "object"
}
data = {
  "id": 1,
  "name": "A green door",
  "price": 12.5,
  "checked": False,
  "tags": [
    "home",
    "green"
  ]
}
jsonschema.validate(data, schema)
data = {
# "id": 1,
  "name": "A green door",
  "price": 12.5,
  "checked": False,
  "tags": [
    "home",
    "green"
  ]
}jsonschema.validate(data, schema)
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jsonschema/validators.py", line 541, in validatecls(schema, *args, **kwargs).validate(instance)File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jsonschema/validators.py", line 130, in validateraise errorjsonschema.exceptions.ValidationError: 'id' is a required propertyFailed validating 'required' in schema:{'$schema': 'http://json-schema.org/draft-04/schema#','properties': {'checked': {'type': 'boolean'},'id': {'type': 'integer'},'name': {'type': 'string'},'price': {'type': 'number'},'tags': {'items': {'type': 'string'},'type': 'array'}},'required': ['id', 'name'],'type': 'object'}On instance:{'checked': False,'name': 'A green door','price': 12.5,'tags': ['home', 'green']}
try:
    jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
    print('Invalid JSON - {0}'.format(e.message))
Invalid JSON - 'id' is a required property
Invalid JSON - 'home' is not of type 'array'

まとめ

VELTRA Engineering

Posts from the VELTRA Engineering team. www.veltra.com

Kunihiko Kido

Written by

木戸 国彦

VELTRA Engineering

Posts from the VELTRA Engineering team. www.veltra.com