考虑以下JSON:
{
"1234abcd" : {
"model" : "civic"
"made" : "toyota"
"year" : "2014"
}
}
考虑另一个JSON:
{
"efgh56789" : {
"model" : "civic"
"made" : "toyota"
"year" : "2014"
}
}
如果密钥是固定的,最外面的字母数字键将变化并且是必需的;让我们说"标识符"然后架构很简单,但由于键名是可变的,我们必须使用patternProperties
,我如何能够提出一个模式来捕获最外层密钥的这些要求:
在ruby中使用json-schema:https://github.com/ruby-json-schema/json-schema。
答案 0 :(得分:12)
当这些属性变量时,您可以做的最好的事情就是使用minProperties
和maxProperties
。如果要说对象中必须只有一个这样的字母数字键,则可以使用以下模式。如果你想说必须至少有一个,你可以省略maxProperties
。
{
"type": "object",
"patternProperties": {
"^[a-z0-9]+$": {
"type": "object",
"properties": {
"model": { "type": "string" },
"make": { "type": "string" },
"year": { "type": "string" }
},
"required": ["model", "make", "year"]
}
},
"additionalProperties": false,
"maxProperties": 1,
"minProperties": 1
}
答案 1 :(得分:7)
您可能需要更改正则表达式以适合您的有效密钥:
{
"patternProperties": {
"^[a-zA-Z0-9]*$":{
"properties": {
"model":{"type":"string"},
"made":{"type":"string"},
"year":{"type":"string"}
}
}
},
"additionalProperties":false
}