Python / jsonschema
===
###### tags: `Python`
###### tags: `Python`, `JSON`, `jsonschema`,`json-schema`, `schema_path`, `validator`, `dict`, `recursively`,`diff`, `string`, `regular expressions`, `numeric types`, `object`, `array`, `boolean`, `null`
<br>
[TOC]
<br>
## Case Study
```python=
json_schema = {
"name": "sculpture_price_calculate",
"description": "Calculate the estimated price to commission a sculpture based on the material and size.",
"parameters": {
"type": "object",
"properties": {
"material": {
"type": "string",
"description": "The material used for the sculpture."
},
"size": {
"type": "integer",
"description": "The size of the sculpture in feet."
},
"complexity": {
"type": "string",
"enum": ["low", "medium", "high"],
"description": "The complexity level of the sculpture.",
"default": "medium"
}
},
"required": ["material", "size"]
}
}
instance = {
"name": "sculpture_price_calculate",
#"description": "Calculate the estimated price to commission a sculpture based on the material and size.",
"parameters": {
"material": "bronze",
"size": 5,
"complexity": "xxx"
}
}
from jsonschema import validate
from jsonschema.exceptions import ValidationError
try:
validate(instance['parameters'], json_schema['parameters'])
except ValidationError as e:
print(e)
print("dir(e):", dir(e))
print(" - absolute_path:", e.absolute_path)
print(" - absolute_schema_path:", e.absolute_schema_path)
print(" - parent:", e.parent)
print(" - path:", e.path)
print(" - relative_path:", e.relative_path)
print(" - relative_schema_path:", e.relative_schema_path)
print(" - schema:", e.schema)
print(" - schema_path:", e.schema_path)
print(" - validator:", e.validator)
print(" - validator_value:", e.validator_value)
print(" - with_traceback:", e.with_traceback)
```
- ### 執行結果:
```
'xxx' is not one of ['low', 'medium', 'high']
Failed validating 'enum' in schema['properties']['complexity']:
{'default': 'medium',
'description': 'The complexity level of the sculpture.',
'enum': ['low', 'medium', 'high'],
'type': 'string'}
On instance['complexity']:
'xxx'
dir(e): ['__annotations__', '__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', '__weakref__', '_contents', '_matches_type', '_set', '_type_checker', '_word_for_instance_in_error_message', '_word_for_schema_in_error_message', 'absolute_path', 'absolute_schema_path', 'args', 'cause', 'context', 'create_from', 'instance', 'json_path', 'message', 'parent', 'path', 'relative_path', 'relative_schema_path', 'schema', 'schema_path', 'validator', 'validator_value', 'with_traceback']
- absolute_path: deque(['complexity'])
- absolute_schema_path: deque(['properties', 'complexity', 'enum'])
- parent: None
- path: deque(['complexity'])
- relative_path: deque(['complexity'])
- relative_schema_path: deque(['properties', 'complexity', 'enum'])
- schema: {'type': 'string', 'enum': ['low', 'medium', 'high'], 'description': 'The complexity level of the sculpture.', 'default': 'medium'}
- schema_path: deque(['properties', 'complexity', 'enum'])
- validator: enum
- validator_value: ['low', 'medium', 'high']
- with_traceback: <built-in method with_traceback of ValidationError object at 0x7fdd86480820>
```
<br>
### 有用的資訊
| attribute | type |
|-----------|------|
| schema | dict |
| schema_path | <class 'collections.deque'> |
| validator | str |
| validator_value | Any |
- 印出錯誤資訊
```python=
print(" - schema:", e.schema)
print(" - schema_path:", list(e.schema_path))
print(" - validator:", e.validator)
print(" - validator_value:", e.validator_value)
```
<br>
### case1 - "xxx" 不在 enum 清單中
```python=
"parameters": {
"material": "bronze",
"size": 5,
"complexity": "xxx" <--- "xxx" 不在清單中
}
```
執行結果
```=
- schema: {'type': 'string', 'enum': ['low', 'medium', 'high'], 'description': 'The complexity level of the sculpture.', 'default': 'medium'}
- schema_path: ['properties', 'complexity', 'enum']
- validator: enum
- validator_value: ['low', 'medium', 'high']
```
<br>
### case2 - 參數缺失
```python=
"required": ["material", "size", "complexity"] <--- 添加 "complexity"
```
執行結果
```=
- schema: {'type': 'object', 'properties': {'material': {'type': 'string', 'description': 'The material used for the sculpture.'}, 'size': {'type': 'integer', 'description': 'The size of the sculpture in feet.'}, 'complexity': {'type': 'string', 'enum': ['low', 'medium', 'high'], 'description': 'The complexity level of the sculpture.', 'default': 'medium'}}, 'required': ['material', 'size', 'complexity']}
- schema_path: ['required']
- validator: required
- validator_value: ['material', 'size', 'complexity']
```
<br>
## 參考資料
- [DeepDiff 7.0.1](https://zepworks.com/deepdiff/current/ignore_types_or_values.html#ignore-string-case)
- [json-schema](https://json-schema.org/understanding-json-schema/reference/)
- [string](https://json-schema.org/understanding-json-schema/reference/string)
- [Regular Expressions](https://json-schema.org/understanding-json-schema/reference/regular_expressions)
- [Numeric types](https://json-schema.org/understanding-json-schema/reference/numeric)
- [object](https://json-schema.org/understanding-json-schema/reference/object)
- [array](https://json-schema.org/understanding-json-schema/reference/array)
- [boolean](https://json-schema.org/understanding-json-schema/reference/boolean)
- [null](https://json-schema.org/understanding-json-schema/reference/null)