用于数据描述与数据验证与输入验证的 JSON 模式

标签 json validation schema jsonschema

在我可以找到的关于使用 JSON 模式的内容中,描述有效数据、验证存储数据和验证输入数据的任务似乎令人困惑(或至少缺乏区别)。

一个典型的例子如下所示:

var schema = {
    type: 'object',
    properties: {
        id: { type: 'integer', required: true },
        name: { type: 'string', required: true },
        description: { type: 'string', required: false }
    }
};

这适用于描述数据存储中的有效数据应该是什么样子,因此用于验证它(后者不是非常有用——如果它在存储中它应该已经有效):
var storedData = {
    id: 123,
    name: 'orange',
    description: 'delicious'
};

它不能很好地验证输入。 id最有可能留给应用程序生成,而不是由用户作为输入的一部分提供。以下输入未通过验证,因为它缺少 id模式声明为 required :
var inputData = {
    name: 'orange',
    description: 'delicious'
};

好吧,有人可能会说,模式不是为了验证直接输入,只有在应用程序添加了 id 之后才应该进行验证。数据就是要存储的内容。

然而,如果模式不是为了验证直接输入,那么 1) JavaScript 验证器在浏览器中运行的点,大概是直接输入,2) 明显面向输入的点 readonly规范中的架构功能?

考虑可以设置一次但不能更新的属性(例如用户名)以及不同的访问级别(例如,管理员和橙子的所有者应该能够更改 description ,而对于其他用户应该留下 readonly )。

处理这个问题的最佳(或至少是有效的)做法是什么?每个用例的不同模式,如下所示?
var baseSchema = {
    type: 'object',
    properties: {
        id: { type: 'integer', required: true },
        name: { type: 'string', required: true },
        description: { type: 'string', required: false }
    }
};

var ownerUpdateSchema = {
    type: 'object',
    properties: {
        id: { type: 'integer', required: false, readonly: true },
        name: { type: 'string', required: true },
        description: { type: 'string', required: false }
    }
};

var userUpdateSchema = {
    type: 'object',
    properties: {
        id: { type: 'integer', required: false, readonly: true },
        name: { type: 'string', required: false, readonly: true },
        description: { type: 'string', required: false, readonly: true }
    }
};

或者是其他东西?

最佳答案

旁注:“required”现在是 v4 中父元素中的一个数组,“readOnly”的大写不同 - 我将在我的示例中使用该表单

我同意验证存储的数据非常罕见。如果你只是描述数据,那么你不需要指定“id”是必需的。

另一件要说的是,这些模式都应该有可以引用它们的 URI(例如 /schemas/baseSchema)。在这一点上,您可以扩展模式以在其中一些模式中使用“id”:

var ownerInputSchema = {
    type: 'object',
    properties: {
        id: {type: 'integer', readOnly: true},
        name: {type: 'string'},
        description: {type: 'string'}
    },
    required: ['name']
};

var userInputSchema = {
    allOf: [{"$ref": "/schemas/inputSchema"}],
    properties: {
        name: {readOnly: true}
    }
};

var storedSchema = {
    allOf: [{"$ref": "/schemas/inputSchema"}],
    required: ["id"]
}

虽然,正如我上面所说,我不确定 storedSchema应该是必要的。您最终得到的是一个描述数据格式的“所有者”模式(由数据所有者提供和可编辑),并且您有一个辅助模式将其扩展为声明 readOnly在额外的属性(property)上。

关于用于数据描述与数据验证与输入验证的 JSON 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048071/

相关文章:

php - 过多的 JSON 响应

regex - Flex 3 正则表达式问题

PHP 和 PostgreSQL,在数据库中注册新用户的最佳实践?

java - XSD 架构更改、XSLT 和向后兼容性

javascript - 如何检查对象结构是否存在?

javascript - 如何在 Angular ui-grid 中显示从 json 到 ui-grid 的数据

python - 如何通过 Django 中的唯一检查避免竞争条件

xml - 将 XML 列表映射到 Word 重复组件 (Word 2013)

javascript - 在 json_encode 输出中获取最后 2 个数据

validation - 在 Spring MVC 网站中验证 URL 参数的最佳方法?