Human-friendly JSON Schema validation for APIs
- Readable and helpful JSON Schema errors
- API-friendly format
- Suggestions for spelling mistakes (using Jaro-Winkler, not the more simplistic Levenshtein) distance algorithm
- Minimal footprint: 1.56 kB (gzip + minified)
$ npm i better-json-schema-errorsAfter validating some data with a compliant JSON Schema validator, pass the errors to betterJsonSchemaErrors
Your JSON Schema Validator should be configured to use the Detailed or Verbose error structure.
import { betterJsonSchemaErrors } from 'better-json-schema-errors';
const valid = validator.validate(schema, data);
if (!valid) {
const betterErrors = betterJsonSchemaErrors({ schema, data, errors: validator.errors });
}Function that formats JSON Schema validation errors in a human-friendly format.
options: BetterJsonSchemaErrorsOptionserrors: ErrorObject[] | null | undefinedYour errors, you will find these in theerrorsproperty of your validator instance (ErrorObjectis a type defined by JSON Schema).data: ObjectThe data you passed to the validator.schema: JSONSchemaThe schema you passed to the validator to validate against.basePath?: stringAn optional base path to prefix paths returned bybetterJsonSchemaErrors. For example, in APIs, it could be useful to use'{requestBody}'or'{queryParemeters}'as a basePath. This will make it clear to users where exactly the error occurred.
ValidationError[]Array of formatted errors (properties ofValidationErrorbelow)message: stringFormatted error messagesuggestion?: stringOptional suggestion based on provided data and schemapath: stringObject path where the error occurred (example:.foo.bar.0.quz)context: { errorType: DefinedError['keyword']; [additionalContext: string]: unknown }errorTypeiserror.keywordproxied from the validator.errorTypecan be used as a key for i18n if needed. There might be additional properties on context, based on the type of error.
