首页 > 解决方案 > JSON Schema 参考解析

问题描述

我有一个包含“$ref”标签的 JSON 模式,我正在尝试获取解析了“$ref”标签的 JSON 模式版本。我只想从 JSON Schema 字符串中的定义(标签)中解析“$ref”(即不需要外部解析)。

是否有执行 JSON Schema 解析的库?(我目前正在使用 org.everit.json.schema 库,这很棒,但我找不到我需要的方法)。

例如,我的原始架构是:

{
  "$id": "https://example.com/arrays.schema.json",
  "description": "A representation of a person, company, organization, or place",
  "title": "complex-schema",
  "type": "object",
  "properties": {
    "fruits": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "vegetables": {
      "type": "array",
      "items": { "$ref": "#/$defs/veggie" }
    }
  },
  "$defs": {
    "veggie": {
      "type": "object",
      "required": [ "veggieName", "veggieLike" ],
      "properties": {
        "veggieName": {
          "type": "string",
          "description": "The name of the vegetable."
        },
        "veggieLike": {
          "type": "boolean",
          "description": "Do I like this vegetable?"
        }
      }
    }
  }
}

这将解决类似这样的问题(注意“#defs/veggie”解析为其在模式中内联插入的定义):

{
  "$id": "https://example.com/arrays.schema.json",
  "description": "A representation of a person, company, organization, or place",
  "title": "complex-schema",
  "type": "object",
  "properties": {
    "fruits": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "vegetables": {
      "type": "array",
      "items": {
        "type": "object",
        "required": [ "veggieName", "veggieLike" ],
        "properties": {
          "veggieName": {
            "type": "string",
            "description": "The name of the vegetable."
          },
          "veggieLike": {
            "type": "boolean",
            "description": "Do I like this vegetable?"
          }
        }
      }
    }
  }
}

标签: jsonjsonschema

解决方案


这在一般意义上是不可能的,因为:

  • $ref 可能是递归的(即再次引用自身)
  • $ref 中的关键字可能与包含模式中的某些关键字重复,这将导致某些逻辑被覆盖。

为什么需要以这种方式更改架构?通常,JSON Schema 实现将在根据提供的数据评估模式时自动解析 $refs。


推荐阅读