Untitled
unknown
javascript
2 years ago
2.9 kB
11
Indexable
/**
* 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();
const uniqueUrls = new Set();
const urlPattern = /^https:\/\/booth\.pm\/en\/items\/\d+$/;
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 nested property is defined and contains string value
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;
// check if nested property contains duplicate value
} else if (uniqueUrls.has(obj[property][nestedProperty].toLowerCase())) {
console.error(`"${nestedProperty}" property in "${property}" contains duplicate value: "${obj[property][nestedProperty]}"`);
return false;
// check if URL is in appropriate format
} else if (!urlPattern.test(obj[property][nestedProperty])) {
console.error(`"${nestedProperty}" property in "${property}" contains invalid URL: "${obj[property][nestedProperty]}"`);
return false;
} else {
// save current value for duplicate matching
uniqueUrls.add(obj[property][nestedProperty].toLowerCase());
}
}
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].replace(/\s/g, '').toLowerCase())) {
console.error(`"${property}" property contains duplicate value: "${obj[property]}"`);
return false;
} else {
// save current value for duplicate matching
uniqueValues.add(obj[property].replace(/\s/g, '').toLowerCase());
}
}
return true;
});
}Editor is loading...
Leave a Comment