Skip to main content
 首页 » 编程设计

使用模式列表的 python jsonschema 验证

2024年10月24日12落叶无声

我正在尝试使用 python 和 jsonschema 模块根据模式验证 json 文件。我的模式由一系列模式组成,其中一个具有基本元素的定义,其余是这些元素和其他对象的集合。

我找不到用于加载模式列表的函数的文档,因此我无法使用它进行验证。我尝试将模式分离到字典中并在 jsonObject 上调用适当的模式,但这不起作用,因为它们相互交叉引用。

如何将所有模式加载/组装为一个模式以进行验证?

我正在尝试加载的部分架构:

[{ 
    "definitions": { 
     "location": { 
       "required": [ 
         "name", 
         "country" 
       ], 
       "additionalProperties": false, 
       "properties": { 
         "country": { 
           "pattern": "^[A-Z]{2}$", 
           "type": "string" 
         }, 
         "name": { 
           "type": "string" 
         } 
       }, 
       "type": "object" 
      } 
    }, 
    "required": [ 
       "type", 
       "content" 
    ], 
    "additionalProperties": false, 
    "properties": { 
     "content": { 
      "additionalProperties": false, 
      "type": "object" 
     }, 
     "type": { 
      "type": "string" 
     } 
    }, 
    "type": "object", 
    "title": "base", 
    "$schema": "http://json-schema.org/draft-04/schema#" 
  }, 
  { 
    "properties": { 
      "content": { 
        "required": [ 
          "address" 
        ], 
        "properties": { 
          "address": { 
            "$ref": "#/definitions/location" 
        } 
      }, 
      "type": { 
        "pattern": "^person$" 
      } 
    } 
  }] 

json 对象看起来像这样:

{ 
 "type":"person", 
 "content":{ 
  "address": { 
   "country": "US", 
   "name" : "1,Street,City,State,US" 
  } 
 } 
} 

请您参考如下方法:

您一次只能针对一个模式进行验证,但该模式可以引用 ($ref) 外部模式。这些引用通常是可用于获取模式的 URI。如果您的架构不公开,文件路径也可能有效。使用您的示例的固定版本,这看起来像这样......

http://your-domain.com/schema/person

{ 
  "$schema": "http://json-schema.org/draft-04/schema#", 
  "title": "Person", 
  "allOf": [{ "$ref": "http://your-domain.com/schema/base#" }], 
  "properties": { 
    "type": { "enum": ["person"] }, 
    "content": { 
      "properties": { 
        "address": { "$ref": "http://your-domain.com/schema/base#/definitions/location" } 
      }, 
      "required": ["address"], 
      "additionalProperties": false 
    } 
  } 
} 

http://your-domain.com/schema/base

{ 
  "$schema": "http://json-schema.org/draft-04/schema#", 
  "title": "base", 
  "type": "object", 
  "properties": { 
    "content": { "type": "object" }, 
    "type": { "type": "string" } 
  }, 
  "required": ["type", "content"], 
  "additionalProperties": false, 
  "definitions": { 
    "location": { 
      "type": "object", 
      "properties": { 
        "country": { 
          "type": "string", 
          "pattern": "^[A-Z]{2}$" 
        }, 
        "name": { "type": "string" } 
      }, 
      "required": ["name", "country"], 
      "additionalProperties": false 
    } 
  } 
} 

一些可能有用的文档