Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...