python - 使用 Cerberus 验证具有严格模式的任意 dict 键
问题描述
我正在尝试验证 JSON,其模式指定具有任意字符串键的 dicts 列表,其对应的值是具有严格模式的 dicts(即,内部 dict 的键严格是一些字符串,这里是 'a' )。从 Cerberus 文档中,我认为我想要的是“keysrules”规则。文档中的示例似乎只显示了如何使用“keysrules”来验证任意键,而不是它们的值。我写了下面的代码作为例子;我能做的最好的就是假设“keysrules”将支持“模式”参数来定义这些值的模式。
keysrules = {
'myDict': {
'type': 'dict',
'keysrules': {
'type': 'string',
'schema': {
'type': 'dict',
'schema': {
'a': {'type': 'string'}
}
}
}
}
}
keysRulesTest = {
'myDict': {
'arbitraryStringKey': {
'a': 'arbitraryStringValue'
},
'anotherArbitraryStringKey': {
'shouldNotValidate': 'arbitraryStringValue'
}
}
}
def test_rules():
v = Validator(keysrules)
if not v.validate(keysRulesTest):
print(v.errors)
assert(0)
这个例子确实验证了,我希望它不在'shouldNotValidate'上验证,因为那个键应该是'a'。'keysrules' 所暗示的灵活性(即,由'keysrules' 管理的键除了{'type': 'string'} 之外没有其他约束)递归地向下传播到它下面的所有模式?还是我犯了一些不同的错误?我怎样才能达到我想要的结果?
解决方案
我不想要keysrules,我想要valuesrules:
keysrules = {
'myDict': {
'type': 'dict',
'valuesrules': {
'type': 'dict',
'schema': {
'a': {'type': 'string'}
}
}
}
}
keysRulesTest = {
'myDict': {
'arbitraryStringKey': {
'a': 'arbitraryStringValue'
},
'anotherArbitraryStringKey': {
'shouldNotValidate': 'arbitraryStringValue'
}
}
}
def test_rules():
v = Validator(keysrules)
if not v.validate(keysRulesTest):
print(v.errors)
assert(0)
这产生了我想要的结果。
推荐阅读
- deep-learning - 在每个 epoch 之后训练 MNIST 数据集时如何输出准确度和损失
- c++ - 如何在 C++ 中的最后一个数字/输出循环后删除逗号
- python - 将 dask 转换为 pandas 数据框
- c# - Powershell ProgramFiles 目录脚本
- blazor-client-side - 有东西阻塞了我的线程 - Blazor wasm
- sql - 检查是特定时间范围内的时间
- cordova - Cordova/Phonegap NFC 插件 NDEF_PUSH_DISABLED [已解决]
- actions-on-google - 有人可以帮助我更改我的调用短语吗?
- c++ - 什么时候可以创建“保留”标识符?
- java - 带有联接的 Spring JPA Costum 返回类型