代码之家  ›  专栏  ›  技术社区  ›  NeoWang

如何在jsonschema中描述这个验证需求?

  •  0
  • NeoWang  · 技术社区  · 10 年前

    我想这样验证我的API json响应:

    {
      "code": 0,
      "results": [
         {"type":1, "abc": 123},
         {"type":2, "def": 456}
      ]
    }
    

    我想验证结果中的对象在类型为1时是否具有“abc”字段,在类型为2时是否有“def”字段。结果可能包含任意数量的type1和type2对象。

    我可以用jsonschema指定这个吗?或者必须对中的元素使用通用验证器 results 然后自己验证?

    1 回复  |  直到 10 年前
        1
  •  1
  •   Jason Desrosiers    10 年前

    您可以使用 anyOf 关键字。

    如果实例成功地针对由该关键字的值定义的至少一个模式进行了验证,则该实例将成功地针对该关键字进行验证。

    http://json-schema.org/latest/json-schema-validation.html#anchor85

    您需要定义这两种类型的项目,然后使用 任意的 描述“结果”的数组项。

    {
      "type": "object",
      "properties": {
        "code": { "type": "integer" },
        "results": {
          "type": "array",
          "items": { "$ref": "#/definitions/resultItems" }
        }
      },
      "definitions": {
        "resultItems": {
          "type": "object",
          "anyOf": [
            { "$ref": "#/definitions/type1" },
            { "$ref": "#/definitions/type2" }
          ]
        },
        "type1": {
          "properties": {
            "type": { "enum": [1] },
            "abc": { "type": "integer" }
          },
          "required": ["abc"]
        },
        "type2": {
          "properties": {
            "type": { "enum": [2] },
            "def": { "type": "integer" }
          },
          "required": ["def"]
        }
      }
    }