kpr-utils/templates/json.html

135 lines
3.5 KiB
HTML
Raw Normal View History

2025-05-21 05:50:10 +00:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>JSON Formatter &amp; Validator</title>
<style>
body {
font-family: sans-serif;
padding: 1rem;
}
h1 {
text-align: center;
margin-bottom: 1rem;
}
.container {
display: flex;
gap: 1rem;
width: 80%;
margin: auto;
}
.pane {
flex: 1;
display: flex;
flex-direction: column;
}
.pane label {
font-weight: bold;
margin-bottom: 0.25rem;
}
.pane textarea {
flex: 1;
width: 100%;
padding: 0.5rem;
font-family: monospace;
font-size: 0.9rem;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
.controls {
margin-top: 0.5rem;
display: flex;
gap: 0.5rem;
}
.controls button {
padding: 0.4rem 0.8rem;
cursor: pointer;
}
.error {
color: #c00;
margin-top: 0.5rem;
min-height: 1.2em;
}
</style>
</head>
<body>
<div class="container">
<!-- Input pane -->
<div class="pane">
<label for="input-json">Input JSON</label>
<textarea id="input-json" placeholder="Paste or type JSON here…"></textarea>
</div>
<!-- Output pane -->
<div class="pane">
<label for="output-json">Formatted JSON</label>
<textarea id="output-json" readonly placeholder="Valid JSON will appear here…"></textarea>
<div id="error" class="error"></div>
<div class="controls">
<button id="copy-btn">Copy Formatted</button>
<button id="clear-btn">Clear All</button>
</div>
</div>
</div>
<script>
const inTA = document.getElementById('input-json');
const outTA = document.getElementById('output-json');
const errDiv = document.getElementById('error');
const copyBtn = document.getElementById('copy-btn');
const clearBtn = document.getElementById('clear-btn');
function formatJSON() {
const text = inTA.value.trim();
if (!text) {
outTA.value = '';
errDiv.textContent = '';
return;
}
try {
const obj = JSON.parse(text);
outTA.value = JSON.stringify(obj, null, 2);
errDiv.textContent = '';
} catch (e) {
outTA.value = '';
errDiv.textContent = '❌ ' + e.message;
}
}
// Live update on input
inTA.addEventListener('input', formatJSON);
// Copy formatted JSON
copyBtn.addEventListener('click', () => {
if (!outTA.value) return;
navigator.clipboard.writeText(outTA.value)
.then(() => alert('Formatted JSON copied!'));
});
// Clear both panes
clearBtn.addEventListener('click', () => {
inTA.value = '';
outTA.value = '';
errDiv.textContent = '';
inTA.focus();
});
// Initialize
window.addEventListener('DOMContentLoaded', () => {
clearBtn.click();
});
</script>
</body>
</html>