Ask Your Question
3

What is the process for validating JSON with an Avro schema in Node.js that can provide a list of errors specifying the data errors that occurred?

asked 2022-08-09 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-02-23 18:00:00 +0000

scrum gravatar image
  1. Install the "avsc" package in Node.js using npm:
npm install avsc
  1. Define your Avro schema in a separate file, including any necessary types or fields. For example, a simple schema for a person might look like this:
{
  "type": "record",
  "name": "Person",
  "fields": [
    { "name": "name", "type": "string" },
    { "name": "age", "type": "int" }
  ]
}
  1. In your Node.js application, load both the Avro schema and the JSON data you want to validate:
var avsc = require('avsc');
var personSchema = avsc.parse(fs.readFileSync('person.avsc'));
var jsonData = JSON.parse(fs.readFileSync('person.json'));
  1. Use the Avro schema to create a new validator object:
var validator = personSchema.createValidator();
  1. Validate your JSON data using the validator object:
var valid = validator(jsonData);
  1. If any errors occurred during validation, the "valid" variable will be false, and the "validator.errors" property will contain an array of error messages. For example:
if (!valid) {
  console.log('Validation errors:');
  console.log(validator.errors);
} else {
  console.log('Data is valid!');
}

This will output a list of any errors that occurred during validation, including information about the field or type that caused the error.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-09 11:00:00 +0000

Seen: 7 times

Last updated: Feb 23 '22