jsonschema 检查键是否存在

jsonschema check if key exists

我有 JSON:

{"price" : 12}

和架构:

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

它用于验证值的类型 validate({"price" : 12}, schema)。 但是 JSON 就像:

{"price_blabla" : 'blabla'}

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

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

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

样本:

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

validate({"price_blabla" : 'blabla'}, schema)

这将引发以下错误。

jsonschema.exceptions.ValidationError: 'price' is a required property

参考:

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