Ajv: Upon error, does `ajv` also display the line number details ?

Created on 19 Apr 2018  路  5Comments  路  Source: ajv-validator/ajv

When loading a json file which will be validated against a schema and if there is any validation error, does ajv show the line number (i.e. position of the property in error) from the json string?

usage

Most helpful comment

In order to save others the hour it took me to get it right:

const ajv = require('ajv');

const validator = new ajv({
  allErrors: true,  // do not bail, optional
  jsonPointers: true,  // totally needed for this
});

function assertValid(schema, subject) {
  const valid = validator.validate(schema, subject);

  if (!valid) {
    let errorMessage = '';
    const sourceMap = jsonSourceMap.stringify(subject, null, 2);
    const jsonLines = sourceMap.json.split('\n');
    validator.errors.forEach(error => {
      errorMessage += '\n\n' + validator.errorsText([ error ]);
      let errorPointer = sourceMap.pointers[error.dataPath];
      errorMessage += '\n> ' + jsonLines.slice(errorPointer.value.line, errorPointer.valueEnd.line).join('\n> ');
    });
    throw new Error(errorMessage);
  }
}

All 5 comments

Ajv doesn鈥檛 work with JSON strings, only with objects. It returns JS or JSON-pointers in errors. You can use json-source-map to map them to locations in JSON strings

Thank you! The json-source-map works great for my requirement. :-)

@vivekgalatage could you point me to an example on how you achieved that please?

@vivekgalatage , Do you have any small example to share how you used json-source-map for custom errors.

In order to save others the hour it took me to get it right:

const ajv = require('ajv');

const validator = new ajv({
  allErrors: true,  // do not bail, optional
  jsonPointers: true,  // totally needed for this
});

function assertValid(schema, subject) {
  const valid = validator.validate(schema, subject);

  if (!valid) {
    let errorMessage = '';
    const sourceMap = jsonSourceMap.stringify(subject, null, 2);
    const jsonLines = sourceMap.json.split('\n');
    validator.errors.forEach(error => {
      errorMessage += '\n\n' + validator.errorsText([ error ]);
      let errorPointer = sourceMap.pointers[error.dataPath];
      errorMessage += '\n> ' + jsonLines.slice(errorPointer.value.line, errorPointer.valueEnd.line).join('\n> ');
    });
    throw new Error(errorMessage);
  }
}
Was this page helpful?
0 / 5 - 0 ratings