Express that, for a given property value, a property with the same name should exist using json schema?

我怕爱的太早我们不能终老 提交于 2019-11-28 11:40:58

问题


I'm trying to validate json files which have an element that has a property which contains a value that should exist in another part of the json. I'm using jsonschema Draft 07.

This is a simple little example that shows the scenario I'm trying to validate in my data.

{
  "objects": {
    "object1": {
      "colorKey": "orange"
    }
  },
  "colors": {
      "orange": {
          "red": "FF",
          "green": "AF",
          "blue": "00"
      }
  }
}

How can I validate that the 'value' of colorKey (in this case 'orange') actually exists as a property of the 'colors' object? The data isn't stored in arrays, just defined properties.


回答1:


For official JSON Schema... You cannot check that a key in the data is the same as a value of the data. You cannot extract the value of data from your JSON instance to use in your JSON Schema.

That being said, ajv, the most popular validator, implements some unofficial extensions. One of which is $data.

Example taken from: https://github.com/epoberezkin/ajv#data-reference

var ajv = new Ajv({$data: true});

var schema = {
  "properties": {
    "smaller": {
      "type": "number",
      "maximum": { "$data": "1/larger" }
    },
    "larger": { "type": "number" }
  }
};

var validData = {
  smaller: 5,
  larger: 7
};

ajv.validate(schema, validData); // true

This would not work for anyone else using your schemas.



来源:https://stackoverflow.com/questions/55691332/express-that-for-a-given-property-value-a-property-with-the-same-name-should-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!