[英]Validating arbitrary dict keys with strict schemas with Cerberus
我正在嘗試驗證 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)
這產生了我想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.