【问题标题】:JSON Schema reference resolutionJSON Schema 参考解析
【发布时间】:2021-10-18 21:05:33
【问题描述】:

我有一个包含“$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?"
          }
        }
      }
    }
  }
}

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

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

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

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

    【讨论】:

    • 可能存在递归错误,但它们会/应该在任何验证工作中被捕获。至于我为什么需要它:我的应用程序需要完全解析的 JSON 模式,因为它用于处理我的应用程序的下游请求(但这可能与我的原始请求无关)。我可能可以做一些简单的 JSON 解析(并用定义替换 $ref 标记),但是正如您强调的那样,可能会出现复杂情况,这就是为什么我正在寻找一个这样做的库......
    • “为您的应用程序处理下游请求”?您没有为此使用 JSON Schema 评估器吗?它将在运行时为您动态解析 $refs。递归不是错误,它是一个特性:)
    • 我的下游应用程序需要一个 JSON 模式,它可以转换为另一种格式,但不幸的是,下游应用程序无法使用 $refs 处理 JSON 模式(而且它很旧,不受我的控制,我无法更改它)所以我需要解决 $ref ......无论哪种方式,解决方案都应该能够接受递归并确定它是否有效......
    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多