Untitled

mail@pastecode.io avatar
unknown
javascript
a month ago
1.9 kB
3
Indexable
Never
/**
 * Validates values of JSON objects 
 * @param {JSON} jsonObj - JSON object to validate
 * @returns {boolean} True if JSON data is valid, otherwise false
 */
const validateJSONData = jsonObj => {
    const parsedData = JSON.parse(jsonObj);
    const uniqueValues = new Set();
    
    return parsedData.every(obj => {
        // loop over JSON objects
        for (const property in obj) {
            // loop over nested object (which is 'credits' property)
            if (property === 'credits') {
                for (const nestedProperty in obj[property]) {
                    // check if property is defined and contains string values 
                    if (!obj[property][nestedProperty] || typeof obj[property][nestedProperty] !== 'string') {
                        console.error(`"${nestedProperty}" property in "${property}" is not valid. Expected non-empty string, received: ${obj[property][nestedProperty]}`);
                        return false;
                    }
                }
                continue;
            } 
            // check if property is defined and contains string value
            if (!obj[property] || typeof obj[property] !== 'string') {
                console.error(`"${property}" property is not valid. Expected non-empty string, received: ${obj[property]}`);
                return false
            // check if `fileName` or `name` property contains duplicate values
            } else if ((property === 'fileName' || property === 'name') && uniqueValues.has(obj[property].trim().toLowerCase())) {
                console.error(`"${property}" property contains duplicate value: "${obj[property]}"`);
                return false;
            } else {
                // save current value for duplicate matching
                uniqueValues.add(obj[property].trim().toLowerCase());
            }         
        }
        
        return true;
    });
}
Leave a Comment