1. /**
  2. * Cleans JSON data for debugging with a timeout.
  3. *
  4. * @param {object} data The JSON data to clean.
  5. * @param {number} timeout The timeout in milliseconds.
  6. * @returns {object} The cleaned JSON data. Returns null if timeout is exceeded.
  7. */
  8. function cleanJsonWithTimeout(data, timeout) {
  9. let startTime = Date.now();
  10. function processObject(obj) {
  11. if (typeof obj === 'object' && obj !== null) {
  12. if (Array.isArray(obj)) {
  13. for (let i = 0; i < obj.length; i++) {
  14. processObject(obj[i]);
  15. }
  16. } else {
  17. for (const key in obj) {
  18. if (obj.hasOwnProperty(key)) {
  19. if (typeof obj[key] === 'string') {
  20. // Trim whitespace
  21. obj[key] = obj[key].trim();
  22. } else if (typeof obj[key] === 'number') {
  23. // Convert to number, handle NaN
  24. obj[key] = Number(obj[key]);
  25. if (isNaN(obj[key])) {
  26. obj[key] = null; // or a default value
  27. }
  28. } else if (typeof obj[key] === 'boolean') {
  29. obj[key] = obj[key].toLowerCase() === 'true';
  30. } else if (typeof obj[key] === 'object') {
  31. processObject(obj[key]);
  32. }
  33. // else leave as is
  34. }
  35. }
  36. }
  37. }
  38. }
  39. function execute() {
  40. try {
  41. processObject(data);
  42. return data;
  43. } catch (e) {
  44. console.error("Error during JSON cleaning:", e);
  45. return null;
  46. }
  47. }
  48. const timeoutId = setTimeout(() => {
  49. console.warn("JSON cleaning timed out.");
  50. return null;
  51. }, timeout);
  52. const cleanedData = execute();
  53. clearTimeout(timeoutId);
  54. return cleanedData;
  55. }

Add your comment