-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathincomplete-json-printer.html
75 lines (70 loc) · 2.06 KB
/
incomplete-json-printer.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Incomplete 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>Incomplete JSON Pretty Printer</h2>
<p>Pretty-print JSON even if it is truncated and not a full document.</p>
<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>