[英]JSON Schema with unknown property names
我想在对象数组中有一个带有未知属性名称的 JSON 模式。 一个很好的例子是网页的元数据:
"meta": {
"type": "array",
"items": {
"type": "object",
"properties": {
"unknown-attribute-1": {
"type": "string"
},
"unknown-attribute-2": {
"type": "string"
},
...
}
}
}
请问有什么想法,或者其他方法可以达到同样的效果吗?
使用patternProperties
而不是properties
。 在下面的示例中,模式匹配正则表达式.*
接受任何属性名称,并且我仅通过使用"additionalProperties": false
来允许string
或null
类型。
"patternProperties": {
"^.*$": {
"anyOf": [
{"type": "string"},
{"type": "null"}
]
}
},
"additionalProperties": false
...或者如果您只想在“对象”中允许一个字符串(就像在原始问题中一样):
"patternProperties": {
"^.*$": {
{"type": "string"},
}
},
"additionalProperties": false
您可以对未明确定义的属性进行约束。 以下模式将“元”强制为属性为字符串类型的对象数组:
{
"properties" : {
"meta" : {
"type" : "array",
"items" : {
"type" : "object",
"additionalProperties" : {
"type" : "string"
}
}
}
}
}
如果您只想拥有一个字符串数组,您可以使用以下模式:
{
"properties" : {
"meta" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
@jruizaranguren 的解决方案对我有用。 虽然我和定义架构的人一样,但我选择了另一种解决方案
"meta": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"value": {
"type": "string"
}
}
}
}
}
我将对象转换为名称-值对象数组 一个有效 JSON 的示例:
"meta": [
[
{
"name": "http-equiv",
"value": "Content-Type"
},
{
"name": "content",
"value": "text/html; charset=UTF-8"
}
],
[
{
"name": "name",
"value": "author"
},
{
"name": "content",
"value": "Astrid Florence Cassing"
}
]
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.