Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a JSON schema with nested references

I have a JSON schema that references multiple schemas, using the '$ref' parameter whose schemas, in turn, reference other schemas.

For eg.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "allOf": [
    {
      "$ref": "xyz.json"
    }
  ]
}

where schema xyz.json is:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "id": { "type": "string",  "title": "Identifier"},
    "Xid": { "type": "object",  "$ref": "pqr.json", "title": "X Identifier"}
    }
}

Just for the sake of convenience, I've placed them all in a single directory and attempted to validate the schema using a library called Ajv but on compiling the schema I get the error: can't resolve reference #/event.json from id.

How can I possibly validate such a JSON schema? My goal is to create a single JavaScript object model for all the schemas. Thanks.

like image 720
L P Avatar asked Mar 31 '26 07:03

L P


1 Answers

I don't know Ajv, but from looking at the docs, this seems to be accomplishable via the .addSchema method. Add all partial schemas like this (fs.readFileSync from node.js just for the sake of argument, in a browser it could be a XMLHttpRequest):

var main = JSON.parse(fs.readFileSync('main.json'));
var xyz = JSON.parse(fs.readFileSync('xyz.json'));

var avj = new Avj(main);

avj.addSchema(xyz, 'xyz');

and reference it from the main schema with the id you set in the second argument:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "allOf": [
    {
      "$ref": "xyz#"
    }
  ]
}

If you have multiple partial schemas, you can also add them all in an array, if you set the ids as properties:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "xyz",
  ...
}

From my experience with other libraries (the old jayschema), you might need to write xyz# (with a hash at the end) at least for the reference, maybe also for the id parameter.

like image 65
ccprog Avatar answered Apr 02 '26 20:04

ccprog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!