Untitled

mail@pastecode.io avatar
unknown
javascript
a month ago
1.5 kB
8
Indexable
Never
/**
 * Validates that properties of JSON objects are defined and have string values 
 * @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);
    
    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 value 
                    if (!obj[property][nestedProperty] || typeof obj[property][nestedProperty] !== 'string') {
                        // simple error log
                        console.log(`"${nestedProperty}" property in "${property}" does not follow required specification. 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') {
                // simple error log
                console.log(`"${property}" property does not follow required specification. Expected non-empty string, received: ${obj[property]}`);
                return false
            }            
        }
        return true;
    });
}
Leave a Comment