/**
* Validates a JSON object against a predefined schema with default values.
*
* @param {object} data The JSON object to validate.
* @param {object} schema The validation schema. Keys are property names, values are objects with 'type' and 'default' properties.
* @returns {object} An object containing validation errors and the validated data.
*/
function validateJson(data, schema) {
const errors = {};
const validatedData = { ...data }; // Create a copy to avoid modifying the original
for (const property in schema) {
if (schema.hasOwnProperty(property)) {
const schemaDef = schema[property];
const value = validatedData[property];
const type = schemaDef.type;
const defaultValue = schemaDef.default;
if (value === undefined || value === null) {
// Handle missing properties
if (schemaDef.required) {
errors[property] = `Property '${property}' is required.`;
} else {
validatedData[property] = defaultValue; // Use default value if not required
}
continue; // Move to the next property
}
if (typeof value !== type) {
errors[property] = `Property '${property}' must be of type '${type}'.`;
validatedData[property] = defaultValue; // Use default value if type mismatch
continue;
}
}
}
return { errors, data: validatedData };
}
Add your comment