1. /**
  2. * Validates a JSON object against a predefined schema with default values.
  3. *
  4. * @param {object} data The JSON object to validate.
  5. * @param {object} schema The validation schema. Keys are property names, values are objects with 'type' and 'default' properties.
  6. * @returns {object} An object containing validation errors and the validated data.
  7. */
  8. function validateJson(data, schema) {
  9. const errors = {};
  10. const validatedData = { ...data }; // Create a copy to avoid modifying the original
  11. for (const property in schema) {
  12. if (schema.hasOwnProperty(property)) {
  13. const schemaDef = schema[property];
  14. const value = validatedData[property];
  15. const type = schemaDef.type;
  16. const defaultValue = schemaDef.default;
  17. if (value === undefined || value === null) {
  18. // Handle missing properties
  19. if (schemaDef.required) {
  20. errors[property] = `Property '${property}' is required.`;
  21. } else {
  22. validatedData[property] = defaultValue; // Use default value if not required
  23. }
  24. continue; // Move to the next property
  25. }
  26. if (typeof value !== type) {
  27. errors[property] = `Property '${property}' must be of type '${type}'.`;
  28. validatedData[property] = defaultValue; // Use default value if type mismatch
  29. continue;
  30. }
  31. }
  32. }
  33. return { errors, data: validatedData };
  34. }

Add your comment