【问题标题】:Structuring JSON schema with hierarchical definitions使用分层定义构建 JSON 模式
【发布时间】:2022-12-11 13:07:43
【问题描述】:

我是编写 JSON 模式的新手。我想我可以在我的模式文件中使用以下结构。你怎么看,这可行吗?

{
    "properties": {
        "my_object": {
            "$ref": "#/definitions/my_object"
        }
    },
    "formats": {
        "language": {
            "type": "string",
            "pattern": "^[a-z]{2}-[A-Z]{2}$"
        },
        "zipcode": {
            "type": "string",
            "pattern": "\\d{5}-\\d{4}|\\d{5}"
        }
    },
    "definitions": {
        "my_object": {
            "type": "object",
            "properties": {
                "language": {"$ref": "#/formats/language"},
                "zipcode": {"$ref": "#/formats/zipcode"}
            }
        }
    }
}

顶层仅包含对definition 下对象的引用。因为我不止一次需要一些类型和模式对,所以我把它们放在formats 下。

definitions 是 JSON 模式中的关键字吗?至少它在示例中被广泛使用。可以在此处添加您自己的“关键字”,例如formats,还是应该将所有内容都放在definitions 下?

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    虽然很多示例确实使用了definitions,但它已经过时了,推荐的方法是改用$defs。其他密钥仍然支持向后兼容。 See here for more

    因此,我建议将所有子模式保留在 $defs 对象中。仍然可以在 $defs 中对语义相关的子模式进行分组,所以如果你坚持保持区别,你可以这样做:

    {
       "properties":{
          "my_object":{
             "$ref":"#/$defs/my_object"
          }
       },
       "$defs":{
          "my_object":{
             "type":"object",
             "properties":{
                "language":{
                   "$ref":"#/$defs/formats/language"
                },
                "zipcode":{
                   "$ref":"#/$defs/formats/zipcode"
                }
             }
          },
          "formats":{
             "language":{
                "type":"string",
                "pattern":"^[a-z]{2}-[A-Z]{2}$"
             },
             "zipcode":{
                "type":"string",
                "pattern":"\d{5}-\d{4}|\d{5}"
             }
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 2014-08-09
      • 2015-11-14
      相关资源
      最近更新 更多