Skip to content

Instantly share code, notes, and snippets.

@adrianlzt
Last active April 1, 2025 11:29
Show Gist options
  • Save adrianlzt/b46056f3642d1f05af74d9c773fbfba2 to your computer and use it in GitHub Desktop.
Save adrianlzt/b46056f3642d1f05af74d9c773fbfba2 to your computer and use it in GitHub Desktop.
Incomplete JSON pretty printer
<!-- Taken from https://simonwillison.net/2025/Mar/28/incomplete-json-pretty-printer/ -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON Pretty Printer</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f7f7f7;
}
textarea {
width: 100%;
height: 200px;
font-family: monospace;
font-size: 14px;
}
pre {
background: #fff;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
white-space: pre-wrap;
word-wrap: break-word;
}
</style>
</head>
<body>
<h2>JSON Pretty Printer</h2>
<textarea id="inputJson" placeholder="Paste incomplete JSON here..."></textarea>
<br>
<button onclick="prettyPrintJson()">Pretty Print JSON</button>
<h3>Formatted JSON:</h3>
<pre id="outputJson"></pre>
<script>
function prettyPrintJson() {
const input = document.getElementById('inputJson').value;
const formattedJson = prettyFormat(input);
document.getElementById('outputJson').textContent = formattedJson;
}
function prettyFormat(jsonString) {
let result = '';
let indent = 0;
let inString = false;
const indentStep = 2;
for (let i = 0; i < jsonString.length; i++) {
const char = jsonString[i];
const prevChar = i > 0 ? jsonString[i - 1] : '';
if (char === '"' && prevChar !== '\\') {
inString = !inString;
result += char;
} else if (!inString && (char === '{' || char === '[')) {
indent += indentStep;
result += char + '\n' + ' '.repeat(indent);
} else if (!inString && (char === '}' || char === ']')) {
indent -= indentStep;
result += '\n' + ' '.repeat(indent) + char;
} else if (!inString && char === ',') {
result += char + '\n' + ' '.repeat(indent);
} else {
result += char;
}
}
return result;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment