function transformHTMLData(htmlString) {
try {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
const data = [];
// Hardcoded limits - adjust as needed
const maxItems = 100;
const maxTextLength = 200;
const elements = doc.querySelectorAll('div'); // Example: process all divs
let itemCount = 0;
for (const element of elements) {
const textContent = element.textContent.trim();
if (textContent.length > maxTextLength) {
textContent = textContent.substring(0, maxTextLength) + "..."; // Truncate long text
}
// Create a data object
const dataItem = {
id: ++ itemCount, // Simple ID
name: textContent, // Use the text content as the name
// Add other fields as needed - can be derived from element attributes
};
data.push(dataItem);
if (data.length >= maxItems) {
console.warn("Reached maximum items limit. Stopping processing.");
break; // Stop processing if limit reached
}
}
return JSON.stringify(data, null, 2); // Convert to JSON with indentation
} catch (error) {
console.error("Error transforming HTML:", error);
return JSON.stringify({ error: "Transformation failed" }, null, 2);
}
}
Add your comment