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-errors
After 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: BetterJsonSchemaErrorsOptions
errors: ErrorObject[] | null | undefined
Your errors, you will find these in theerrors
property of your validator instance (ErrorObject
is a type defined by JSON Schema).data: Object
The data you passed to the validator.schema: JSONSchema
The schema you passed to the validator to validate against.basePath?: string
An 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 ofValidationError
below)message: string
Formatted error messagesuggestion?: string
Optional suggestion based on provided data and schemapath: string
Object path where the error occurred (example:.foo.bar.0.quz
)context: { errorType: DefinedError['keyword']; [additionalContext: string]: unknown }
errorType
iserror.keyword
proxied from the validator.errorType
can be used as a key for i18n if needed. There might be additional properties on context, based on the type of error.