我怎样才能只允许字典键 "source"、"dest" 和 "keep"(请参阅下面的 config.json)作为 json 模式中的字典键?

How can I allow only the dictionary keys "source", "dest" and "keep" (see: config.json below) as dictionary keys in json schema?

如何只允许字典键 "source"、"dest" 和 "keep"(参见:下面的 config.json)作为 json 模式中的字典键?

"required": ["snapshots"]"additionalProperties": False 一起使用我设法只允许键 "snapshots",但这样做类似于键 "string" 的字典值("required": ["source","dest", "keep"]) 没有将所需的约束添加到我的 json 配置中。

我测试了后者,通过改变例如我的 config.json 文件中的 "source" 到 "somethingElse" 的键,但是 jsonschema.validate() 没有引发任何错误,尽管我希望如此。

schemaTest.py:

import json
from jsonschema import validate

schema = {
             "$schema": "http://json-schema.org/schema",
             "required": ["snapshots"],
             "additionalProperties": False,
             "properties":
             {
                 "snapshots":
                 {
                     "type": "object",
                     "properties":
                     {
                         "string":
                         {
                             "type": "object",
                             "items": { "type": "string" },
                             "uniqueItems": True,
                             "properties":
                             {
                                 "source": {"type": "string"},
                                 "dest": {"type": "string"},
                                 "keep": {"type": "string"}
                             },
                             "required": ["source","dest", "keep"],
                             "additionalProperties": False
                         }
                     }
                 }
             }
         }

path = "/home/user/test/config.json"
jsonConfig = json.load(open(path))
print(validate(jsonConfig, schema))

config.JSON:

{
    "snapshots":
    {
        "@snapshot1":
        {
            "source": "/mnt/subvolContainer/@snapshot1",
            "dest": "/mnt/subvolContainer/",
            "keep": "w=10,m=10"
        },
        "@snapshot2":
        {
            "source": "/mnt/subvolContainer/@snapshot2",
            "dest": "/mnt/subvolContainer/",
            "keep": "w=10,m=10"
        }
    }
} 

您在快照对象的定义中有一些额外的嵌套层。例如,string 不是您正在使用的 属性 名称。要验证对象中未知键的子项的属性,您需要将类型 放在 对象 additionalProperties 中。 itemsuniqueItems 适用于数组,不适用于对象。

这个有效:

schema = {
  "$schema": "http://json-schema.org/schema",
  "required": ["snapshots"],
  "additionalProperties": False,
  "properties":
  {
    "snapshots":
    {
      "type": "object",
      "additionalProperties":
      {
        "type": "object",
        "properties":
        {
          "source": {"type": "string"},
          "dest": {"type": "string"},
          "keep": {"type": "string"}
        },
        "required": ["source","dest", "keep"],
        "additionalProperties": False
      }
    }
  }
}