LoginSignup
8
6

More than 5 years have passed since last update.

任意のキーを取る辞書のJSON Schema記法の覚書

Posted at

JSON Schema

任意のキーと、文字列か数値を値とする辞書型をvalidationするためのJSON schema記法例。

JSON-schema
{
    "type": "object",
    "additionalProperties": {
        "anyOf": [
            {"type": "string"},
            {"type": "number"},
        ],
    },
}

Example@python

前述のスキーマをPython上でjsonschemaモジュールを使用して実行した例。

import jsonschema

schema = {
    "type": "object",
    "additionalProperties": {
        "anyOf": [
            {"type": "string"},
            {"type": "number"},
        ],
    },
}

valid_obj = {
    "key_a" : "value",
    "key_b" : 1,
    "key_c" : 1.1,
}
invalid_obj = {
    "key_a" : "value",
    "key_b" : 1,
    "key_c" : None,
}

jsonschema.validate(valid_obj, schema)

try:
    jsonschema.validate(invalid_obj, schema)
except jsonschema.ValidationError as e:
    print(e)
None is not valid under any of the given schemas

Failed validating 'anyOf' in schema['additionalProperties']:
    {'anyOf': [{'type': 'string'}, {'type': 'number'}]}

On instance['key_c']:
    None

参考

Dictionary-like JSON schema - Stack Overflow
http://stackoverflow.com/questions/27357861/dictionary-like-json-schema

python - JSON schema validation with arbitrary keys - Stack Overflow
http://stackoverflow.com/questions/16081118/json-schema-validation-with-arbitrary-keys

8
6
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
8
6