jsonschema 检查 key 是否存在

stk*_*ubr 2 python json jsonschema

我有 JSON:

{"price" : 12}
Run Code Online (Sandbox Code Playgroud)

和架构:

schema = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"}
    },
}
Run Code Online (Sandbox Code Playgroud)

它的作用是验证 value 的类型validate({"price" : 12}, schema)。然而 JSON 喜欢:

{"price_blabla" : 'blabla'}
Run Code Online (Sandbox Code Playgroud)

也被认为是有效的。我应该如何更改架构以便它检查 JSON 是否包含特定键?基本上我有很多 JSON,我需要获取所有具有特定模式的 JSON。

Kar*_* KR 6

  • 在 jsonschema 中有一个名为 的属性'required',使用该字段我们可以检查 JSON 是否包含特定的键。

  • 缺少必填字段属性会使 JSON 文档无效。

样本:

schema = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"}
    },"required": ["price"]
}

validate({"price_blabla" : 'blabla'}, schema)
Run Code Online (Sandbox Code Playgroud)

这将引发以下错误。

jsonschema.exceptions.ValidationError: 'price' is a required property
Run Code Online (Sandbox Code Playgroud)

参考 :

https://json-schema.org/understanding-json-schema/reference/object.html#required