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在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"]
}
}
}

是的,您可以在其他文档中引用模式,但是uri必须是正确的,并且如果这些文件在网络或文件系统中不可用,您需要手动将它们添加到评估器中。

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

最新更新