微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

您可以为 json 子模式使用单独的文件吗?

如何解决您可以为 json 子模式使用单独的文件吗?

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

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

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

对于我做错了什么,任何帮助将不胜感激。

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

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","title":"Metric Schema","description":"Schema of metric data.","required": ["metric_name"],"properties": {
        "metric_name":{
            "description": "The name of the metric in standard English. e.g. Live Views (Millions)","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"]
        }
    }
}

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。