Question
How can I validate a JSON string against a schema programmatically?
// Example using JSON Schema Validator in Node.js
const Validator = require('jsonschema').Validator;
const v = new Validator();
const schema = {
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" }
},
"required": ["name", "age"]
};
const jsonData = {
"name": "John Doe",
"age": 30
};
const validationResult = v.validate(jsonData, schema);
if (validationResult.valid) {
console.log('JSON is valid.');
} else {
console.log('JSON is invalid:', validationResult.errors);
}
Answer
Validating a JSON string against a schema ensures that the data adheres to the expected structure and types. This process is crucial for maintaining data integrity and can be accomplished using various libraries across programming languages.
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' }
},
required: ['name', 'age']
};
const data = {
name: 'Jane Doe',
age: 'thirty' // Invalid data type
};
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
console.error(validate.errors);
} else {
console.log('Data is valid!');
}
Causes
- Mistyped JSON structure.
- Incorrect data types that do not match the schema requirements.
- Missing required fields as defined in the schema.
Solutions
- Use JSON Schema to define a clear structure for the JSON data.
- Employ popular libraries like `jsonschema` for Node.js or `ajv` for JavaScript to perform the validation programmatically.
- Handle and log validation errors to improve data quality.
Common Mistakes
Mistake: Not defining required properties in the schema.
Solution: Ensure that all required fields are specified in your schema.
Mistake: Using JavaScript objects instead of proper JSON syntax.
Solution: Make sure to validate well-formed JSON strings.
Mistake: Ignoring validation results and proceeding with invalid data.
Solution: Always check validation results before further processing.
Helpers
- validate JSON
- JSON schema validation
- programmatically validate JSON
- JSON schema
- JSON validation libraries