40

我有以下 JSON 输出数据:

{
   "label_name_0" : 0,
   "label_name_5" : 3,
   .
   .
   .
   "label_name_XXX" : 4
}

输出很简单:与整数值关联的 key[1] 名称。如果键名没有改变,我可以很容易地想出类似于这样的 JSON Schema:

    {
        "type": "array"
        "title": "Data output",
        "items" :{ 
            "properties": {
                "label_name": {
                   "type": "integer",
                   "default": 0,
                   "readonly": True,
            }
        }
    },

由于键名本身是未知的并且不断变化,因此我必须为其设计架构。我唯一知道的是,密钥string不超过 100 个字符。如何为lable_name_xxx不断变化的键定义 JSON 模式。

[1] 不确定我是否使用了正确的术语

4

3 回答 3

51

On json-schema.org you will find something appropriate in the File System Example section. You can define patternProperties inside an object.

{
    "type": "object",
    "properties": {
        "/": {}
    },
    "patternProperties": {
        "^(label_name_[0-9]+)+$": { "type": "integer" }
    },
    "additionalProperties": false,
 }

The regular expression (label_name_[0-9]+)+ should fit your needs. In JSON Schema regular expressions are explicitly anchored with ^ and $. The regular expressions defines, that there has to be at least one property (+). The property consists of label_name_ and a number between 0 and 9 whereas there has to be at least one number ([0-9]+), but there can also arbitrary many of them.

By setting additionalProperties to false it constrains object properties to match the regular expression.

于 2013-08-19T12:30:03.760 回答
25

正如康拉德的回答所说,使用patternProperties. 但是使用 代替properties,这不是必需的,我认为 Konrad 只是从他的参考示例中粘贴了该示例,该示例期望路径以/. 在下面的示例中,模式匹配regex .*接受任何属性名称,并且我只允许使用字符串或 null 类型"additionalProperties": false

  "patternProperties": {
    "^.*$": {
      "anyOf": [
        {"type": "string"},
        {"type": "null"}
      ]
    }
  },
  "additionalProperties": false
于 2017-02-20T16:40:05.003 回答
0

比 patternProperties 更简单的解决方案,因为 OP 对键名(文档)没有任何要求:

{
    "type": "object",
    "additionalProperties": {
        "type": "integer",
        "default": 0,
        "readonly": true,
    }        
}

defaultreadonly包括在内,因为它们已包含在 OP 的初始建议中,但不是必需的。

于 2021-11-02T13:50:22.507 回答