Warm tip: This article is reproduced from serverfault.com, please click

python-我可以在JSON模式中使用$ ref来引用另一个对象中的对象吗?

(python - Can I use $ref in JSON Schema to refer to object from another object?)

发布于 2020-12-03 18:05:37

在下面的示例架构中,我基本上要要求reporting_personinincident对象是数组中person引用对象people这可能吗?

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "definitions": {
      "person": {
        "type": "object",
        "properties": {
          "person_id": {
            "type": "integer"
          },
          "first_name": {
            "type": "string"
  
          }
        }
      },
      "incident": {
        "type": "object",
        "properties": {
          "incident_id": {
            "type": "integer"
          },
          "description": {
            "type": "string"
          },
          "reporting_person": {
            "type": "string",
            "$ref": "#/people/person_id"
          }
      }}
    },
    "type": "object",
    "properties": {
        "root" :{
            "type" : "object",
            "properties": {
                "people" : {
                    "type" :"array",
                    "items" : { "$ref": "#/definitions/person"}
                },
                "incidents" : {
                    "type" : "array",
                    "items": {"$ref": "#/definitions/incident"}
                }
              }
            }
        }
  }

我的另一种选择是仅使用模式定义ID标准,然后将确认移至应用程序代码,但是如果不在模式中进行这种排序数据有效性确认,将是很可惜的。谢谢

Questioner
EddyWD
Viewed
11
Jason Desrosiers 2020-12-04 06:10:21

你可以$ref用来在任何地方引用任何模式。在这种情况下,你$ref应为"#/definitions/person/properties/person_id但是,通常为“ person_id”创建定义并引用它而不是指向属性是更干净的方法。

我还注意到你"type": "string旁边还有一个$reftype将被忽略。如果$ref该对象中存在,则该对象将被视为引用,而不是架构。因此,“类型”不被评估为type关键字。这只是参考中的噪音。