Express that, for a given property value, a proper

2020-02-15 03:25发布

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条回答
劫难
2楼-- · 2020-02-15 03:54

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.

查看更多
登录 后发表回答