/**
* Cleans JSON data for debugging with a timeout.
*
* @param {object} data The JSON data to clean.
* @param {number} timeout The timeout in milliseconds.
* @returns {object} The cleaned JSON data. Returns null if timeout is exceeded.
*/
function cleanJsonWithTimeout(data, timeout) {
let startTime = Date.now();
function processObject(obj) {
if (typeof obj === 'object' && obj !== null) {
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
processObject(obj[i]);
}
} else {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'string') {
// Trim whitespace
obj[key] = obj[key].trim();
} else if (typeof obj[key] === 'number') {
// Convert to number, handle NaN
obj[key] = Number(obj[key]);
if (isNaN(obj[key])) {
obj[key] = null; // or a default value
}
} else if (typeof obj[key] === 'boolean') {
obj[key] = obj[key].toLowerCase() === 'true';
} else if (typeof obj[key] === 'object') {
processObject(obj[key]);
}
// else leave as is
}
}
}
}
}
function execute() {
try {
processObject(data);
return data;
} catch (e) {
console.error("Error during JSON cleaning:", e);
return null;
}
}
const timeoutId = setTimeout(() => {
console.warn("JSON cleaning timed out.");
return null;
}, timeout);
const cleanedData = execute();
clearTimeout(timeoutId);
return cleanedData;
}
Add your comment