使用任意键进行JSON模式验证 [英] JSON schema validation with arbitrary keys
问题描述
我正在使用validictory来验证附加的JSON数据和架构. 到目前为止工作.
I am using validictory for validating the attached JSON data and schema. Working so far.
但是,数据字典可以具有任意字符串键(但'bp'除外).模式中的键"bp"是硬编码的,它可以是给定列表中的字符串(字符串枚举).如何在此处为字典的第一级"添加枚举定义.
However the data dictionary can have arbitrary string keys (others than 'bp' but). The key 'bp' in the schema here is hard-coded...it can be a string from a given list (enum of string). How do I add the enum definition here for the "first level" of the dict.
import json
import validictory
data = {'bp': [{'category': 'bp',
'created': '2013-03-08T09:14:48.148000',
'day': '2013-03-11T00:00:00',
'id': 'dc049c0e-d19a-4e3e-93ea-66438a239712',
'unit': 'mmHg',
'value': 147.0,
'value2': 43.0}]}
schema = {
"type":"object",
"properties":{
"bp": {
"type":"array",
"required":False,
"items":
{
"type":"object",
"required":False,
"properties":{
"category": {
"type":"string",
"default": "bp",
"required":False
},
"created": {
"type":"string",
"default": "2013-03-08T09:14:48.148000",
"required":False
},
"day": {
"type":"string",
"default": "2013-03-11T00:00:00",
"required":False
},
"id": {
"type":"string",
"default": "dc049c0e-d19a-4e3e-93ea-66438a239712",
"required":False
},
"unit": {
"type":"string",
"default": "mmHg",
"required":False
},
"value2": {
"type":"number",
"default":43,
"required":False
},
"value": {
"type":"number",
"default":147,
"required":False
}
}
}
}
}
}
validictory.validate(data,schema)
推荐答案
这完全取决于您要执行的操作.
It depends on exactly what you're trying to do.
如果您希望使用相同的规范,但要获得一系列属性,则可以抽象出定义:
If you want the same specification, but for a range of properties, you can abstract out the definition:
{
"type": "object",
"properties": {
"bp": {"$ref": "#/definitions/categoryList"},
"foo": {"$ref": "#/definitions/categoryList"},
"bar": {"$ref": "#/definitions/categoryList"}
},
"definitions": {
"categoryList": {...}
}
}
如果希望任何属性遵循该架构,则可以使用additionalProperties
:
If you want any properties to follow that schema, you can use additionalProperties
:
{
"type": "object",
"additionalProperties": {...}
}
或一系列属性(由模式匹配)-例如,任何小写字母:
Or a range of properties (matched by a pattern) - for instance, anything lower-case:
{
"type": "object",
"patternProperties": {
"^[a-z]+$": {...}
}
}
如果要限制可以定义的属性的数量,则可以使用"maxProperties"(仅标准版v4):
If you want to limit the number of properties that can be defined, then you can use "maxProperties" (v4 of the standard only):
{
"type": "object",
"additionalProperties": {...},
"maxProperties": 1
}
P.S. -在标准的v4中,必需"是一个数组.实际上,即使在v3中,"required"也默认为false
,因此您的示例根本不需要它.
P.S. - in v4 of the standard, "required" is an array. In fact, even in v3, "required" defaults to false
, so your example doesn't need it at all
这篇关于使用任意键进行JSON模式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!