【问题标题】:Can you use separate files for json subschemas?您可以为 json 子模式使用单独的文件吗?
【发布时间】:2021-07-27 22:04:03
【问题描述】:

我是使用 JSON 模式的新手,我对子模式很困惑。我做了很多搜索并阅读了https://json-schema.org/understanding-json-schema/structuring.html,但我觉得我没有得到一些基本概念。

我想将一个架构分解为几个文件。例如,我有一个我想嵌套在类别模式中的度量模式。子模式可以是被引用的单独文件,还是与基本模式在同一文件中的代码块?如果它们是单独的文件,您如何引用另一个文件?我尝试使用嵌套文件的 $id 为 $ref 使用很多不同的值,但它似乎不起作用。

我认为我并不真正了解 $id 和 $schema 字段。我已经阅读了他们的文档,但仍然感到困惑。 $id 是否需要是有效的 URI?文档似乎说他们没有。我只是从 jsonschema 站点示例中复制了 $schema 值。

如果我做错了什么,我们将不胜感激。

(在以太回复后添加以下内容) 我得到的错误信息是:

KeyError: 'http://mtm/metric'

和变化

jsonschema.exceptions.RefResolutionError: HTTPConnectionPool(host='mtm', port=80): Max retries exceeded with url: /metric (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe9204a31c0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'))

这是 category_schema.json 中的类别架构:

{
    "$id": "http://mtm/category",
    "$schema":"https://json-schema.org/draft/2020-12/schema",
    "title":"Category Schema",
    "type":"object",
    "required":["category_name", "metrics"],
    "properties": {
        "category_name":{
            "description": "The name of the category.",
            "type":"string"
        },
        "metrics":{
            "description": "The list of metrics for this category.",
            "type":"array",
            "items": { 
                "$ref": "/metric" 
            }
        }
    }
}

这是 metric_schema.json 中的度量模式:

{
    "$id": "http://mtm/metric",
    "$schema":"https://json-schema.org/draft/2020-12/schema",
    "title":"Metric Schema",
    "description":"Schema of metric data.",
    "type":"object",
    "required": ["metric_name"],
    "properties": {
        "metric_name":{
            "description": "The name of the metric in standard English. e.g. Live Views (Millions)",
            "type":"string"
        },
        "metric_format": {
            "description": "The format of the metric value. Can be one of: whole, decimal, percent, or text",
            "type": "string",
            "enum": ["integer", "decimal", "percent", "text"]
        }
    }
}

【问题讨论】:

标签: jsonschema python-jsonschema


【解决方案1】:

是的,您可以在其他文档中引用架构,但 URI 需要正确,如果文件不支持网络或文件系统,则需要手动将文件添加到评估程序。

在您的第一个架构中,您声明其 uri 为“http://mtm/category”。但是你说"$ref": "/mtm/metric"——因为这不是绝对的,$id URI 将用作解析它的基础。完整的 URI 解析为“http://mtm/mtm/metric”,这与第二个模式中使用的标识符不同,因此不会找到该文档。这应该在错误消息中指出(您没有提供)。

【讨论】:

  • 谢谢,Ether,这肯定有助于我更多地理解事情。我在错误日志中看到它是如何解决您所说的问题的。我修改了度量参考以反映相对路径的使用。我得到一个关键错误仍然是一个类似的错误,我将它添加到我的原始帖子中。它是 KeyError:'mtm/metric'。两个文件都在同一个文件夹中。 “如果网络或文件系统不可用,则将文件手动添加到评估器”是什么意思?谢谢:)
  • 您必须查看特定实现的文档以了解如何操作,但一般来说,使用“$ref”引用的文档预计不会是网络可检索的,因此如果您的schema 依赖于外部文档,您需要提前告知评估者它们,以便它可以加载它们并在评估时提供它们。
猜你喜欢
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多