使用验证器(或类似工具)进行Python数据结构验证

10 投票
1 回答
1340 浏览
提问于 2025-04-17 10:50

我正在处理以json格式输入的数据。这些数据需要符合特定的格式,如果不符合,就应该被忽略。目前我用了一堆复杂的“如果...那么...”的判断来检查json文档的格式。

我尝试了一些不同的Python json-schema库,效果还不错,但我仍然可以提交一些在模式中没有描述的键,这让我觉得这个方法没什么用。

这个例子没有抛出异常,虽然我本来期待会有:

#!/usr/bin/python

from jsonschema import Validator
checker = Validator()
schema = {
    "type" : "object",
    "properties" : {
        "source" : {
            "type" : "object",
            "properties" : {
                "name" : {"type" : "string" }
            }
        }
    }
}
data ={
   "source":{
      "name":"blah",
      "bad_key":"This data is not allowed according to the schema."
   }
}
checker.validate(data,schema)

我有两个问题:

  • 我在模式定义中是不是漏掉了什么?
  • 如果没有,还有没有其他简单的方法来解决这个问题?

谢谢,

Jay

1 个回答

9

添加 "additionalProperties": False

#!/usr/bin/python

from jsonschema import Validator
checker = Validator()
schema = {
    "type" : "object",
    "properties" : {
        "source" : {
            "type" : "object",
            "properties" : {
                "name" : {"type" : "string" }
            },
            "additionalProperties": False, # add this
        }
    }
}
data ={
   "source":{
      "name":"blah",
      "bad_key":"This data is not allowed according to the schema."
   }
}
checker.validate(data,schema)

撰写回答