在 JSON 文档中包含架构名称是个好主意吗

Is it a good idea to include schema name in JSON document

我们正在开发一项 public 服务,该服务接收 JSON 条消息并存储在数据库中。

现在这项服务可能是众多服务中的第一项,我正在研究构建 JSON 模式的方法。我们在 XML Schema 方面有很多经验,但是 JSON Schema 对我们来说有点陌生。

其中一个想法是在每个包含 架构名称 的 JSON 架构中包含一个 Header 部分, 主要版本唯一消息ID

这是这种架构的简化版本

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "http://www.example.com/json/01/sampleMessage",
    "type": "object",
    "title": "Sample Message for Whosebug",
    "description": "version 01.01",
    "properties": {
        "Header": {
            "$ref": "#/definitions/Header"
        },
        "EanGsrn": {
            "description": "Unique identifier of the Headpoint.",
            "type": "string",
            "pattern": "^[0-9]{18}$"
        },
        "Sector": {
            "description": "Sector for which the Headpoint is valid.",
            "type": "string",
            "enum": [
                "Electricity", "Gas"
            ]
        }
    },
    "additionalProperties": false,
    "required": [
        "Header", "EanGsrn", "Sector"
    ],
    "definitions": {
        "Header": {
            "id": "#Header",
            "type": "object",
            "description": "Standard header for all messages",
            "properties": {
                "Schema": {
                    "description": "$id of the schema of this message",
                    "type": "string",
                    "enum": ["http://www.example.com/json/01/sampleMessage"]
                },
                "Version": {
                    "description": "The specific version of the shema of this message",
                    "type": "string",
                    "pattern": "^01\.[0-9]{2,3}$"
                },
                "MessageId": {
                    "description": "Unique identifier for the Message",
                    "type": "string",
                    "pattern": "^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"
                }
            },
            "required": [
                "Schema", "Version", "MessageId"
            ],
            "additionalProperties": false
        }
    }
}

这样做的好处应该是:

问题

没有定义 JSON 实例如何识别它应在 HTTP 请求之外符合的模式的“最佳实践”。

用于定义架构的规范 provides a header name,但这仅在您的 JSON 数据始终通过 HTTP 提供时才有效。

其他与您类似的系统已将此信息作为 header 部分包含在 JSON 数据中,但规范本身并未详细说明定义的“最佳实践”或方法。