JSON2HTML / index.html
ShayanRl's picture
Update index.html
a8c95a5 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON to HTML Converter</title>
</head>
<body>
<h2>Paste JSON Below:</h2>
<textarea id="jsonInput" rows="10" cols="50" placeholder="Paste JSON here"></textarea>
<br><br>
<button onclick="convertJson()">Convert JSON to HTML</button>
<h2>Output:</h2>
<div id="output"></div>
<script>
// Recursive function to convert JSON to HTML
function jsonToHtml(data) {
let html = '';
if (Array.isArray(data)) {
html += '<ul>';
data.forEach(item => {
html += `<li>${jsonToHtml(item)}</li>`;
});
html += '</ul>';
} else if (typeof data === 'object' && data !== null) {
for (const key in data) {
if (Array.isArray(data[key]) || typeof data[key] === 'object') {
html += `<div aria-label="${key}">${jsonToHtml(data[key])}</div>`;
} else {
html += `<p aria-label="${key}">${data[key]}</p>`;
}
}
} else {
html += data;
}
return html;
}
// Function to handle JSON input and display HTML
function convertJson() {
const jsonInput = document.getElementById("jsonInput").value;
try {
const jsonData = JSON.parse(jsonInput); // Parse JSON input
const htmlContent = jsonToHtml(jsonData); // Convert to HTML
document.getElementById("output").innerHTML = htmlContent; // Display HTML
} catch (error) {
document.getElementById("output").innerHTML = "<p style='color: red;'>Invalid JSON. Please check the input.</p>";
}
}
</script>
</body>
</html>