python 使用schema对多级嵌套json进行递归校验代码示例
时间: 2024-01-06 11:06:36 浏览: 191
假设我们有一个多级嵌套的 JSON 数据,例如:
```json
{
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"phones": [
{
"type": "home",
"number": "555-555-1234"
},
{
"type": "work",
"number": "555-555-5678"
}
]
}
```
我们可以使用 Python 的 `schema` 模块来定义一个嵌套的校验规则,例如:
```python
from schema import Schema, And, Or, Optional
# 定义嵌套的校验规则
phone_schema = Schema({"type": str, "number": str})
address_schema = Schema(
{
"street": str,
"city": str,
"state": str,
"zip": str,
}
)
person_schema = Schema(
{
"name": str,
"age": int,
"address": address_schema,
"phones": [phone_schema],
Optional("email"): str,
}
)
# 校验数据
data = {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345",
},
"phones": [
{"type": "home", "number": "555-555-1234"},
{"type": "work", "number": "555-555-5678"},
],
}
person_schema.validate(data)
```
在上面的代码中,我们使用 `schema.Schema()` 创建了一个新的校验规则,并使用 `And()`、`Or()`、`Optional()` 等函数来定义校验规则。然后,我们使用 `validate()` 函数来校验数据。如果数据符合校验规则,就不会抛出异常;否则,会抛出异常并显示校验错误信息。
阅读全文