Python json模式验证

Python json模式验证,python,flask,Python,Flask,我正在我的新项目中使用flask框架。它将从post获取JSON数据并发送JSON响应。因此,我需要验证我的JSON请求。我看过几家图书馆。但这些库并没有按预期工作。最后,我决定使用flask jsonschema验证器。它可以很好地处理单个JSON对象。如果请求对象具有嵌套对象,则该对象不工作。比如说, from flask_jsonschema_validator import JSONSchemaValidator JSONSchemaValidator(app=app, root=&qu

我正在我的新项目中使用flask框架。它将从post获取JSON数据并发送JSON响应。因此,我需要验证我的JSON请求。我看过几家图书馆。但这些库并没有按预期工作。最后,我决定使用flask jsonschema验证器。它可以很好地处理单个JSON对象。如果请求对象具有嵌套对象,则该对象不工作。比如说,

from flask_jsonschema_validator import JSONSchemaValidator
JSONSchemaValidator(app=app, root="schemas")
这是我对验证器的初始化

# If any error occurred in the request.
@app.errorhandler(jsonschema.ValidationError)
def json_validation_error(e):
    return json_response("error", str(e), {})
这是我的错误处理程序

@app.validate('模型','保存') def save_model():

这是我的实现

{
  "save": {
    "type": "object",
    "properties": {
      "workspace": {"type": "object"},
      "name": {"type": "string"},
      "description": {"type": "string"},
      "uri": {"type": "string"},
      "type": {
         "name": {"type": "string"},
      }
    },
    "required": [ "workspace", "name", "description", "uri", "type"]
  }
}
这是我的model.json文件。它正在验证除“类型”之外的请求。如何使用嵌套对象对JSON请求应用验证

请帮助任何人解决此问题

提前感谢。

包检查嵌套对象上的变量类型

它在你的路线上起到装饰的作用

SCHEMA = {
    "type": "object",
    "properties": {
      "workspace": {"type": "object"},
      "name": {"type": "string"},
      "description": {"type": "string"},
      "uri": {"type": "string"},
      "type": {
         "type": "object",
         "properties": {
              "name": {"type": "string"},
         }
      }
    },
    "required": ["workspace", "name", "description", "uri", "type"]
}

@expects_json(SCHEMA)
def my_route(self, **kwargs):
    pass

如果要验证复杂的嵌套对象,我建议使用JSONSchema的替代工具。我可以像下面这样复制您的模式验证。如您所见,制定一个验证模式只是由一系列自包含的验证程序函数组成,这些函数可以应用于对象、列表和原语值

来自goodjson.validators的导入是\u dict、是\u string、是\u uri、foreach\u key 验证\u fun=foreach\u键( save=[foreach\u键( 工作空间=[is_dict], 名称=[是字符串], description=[是字符串], uri=[is_uri], type=[foreach\u键( name=[是字符串] )] )] ) 验证\u fun(您的\u JSON\u数据\u对象)
免责声明:我是GoodJSON的作者。

感谢您的回复。我已经这样试过了。它起作用了。但验证在类型对象中不起作用。我是否应该在要求的部分给出“type.name”。但这也不起作用。我已经上传了我的答案。我没有正确更新json模式。当您有一个类型为“object”的变量时,您必须指定它。然后您可以定义它的
属性
。谢谢。很好用。我们如何以JSON格式发送错误消息?目前,它以最简单和最好的方式显示HTML格式。是实现一个自定义错误。下面是一个示例:可能在
类型
对象中添加
必需的
属性:
“类型”:{“类型”:“对象”,“属性”:{“名称”:{“类型”:“字符串”},},“必需”:[“名称”]}