-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
336 lines (299 loc) · 10.5 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON deep decode</title>
<link rel="icon" href="https://cdn.icon-icons.com/icons2/2248/PNG/512/code_json_icon_136758.png" type="image/x-icon">
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous"
>
<style>
#input-container textarea {
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div id="header-container">
<br>
<h1>JSON deep decode</h1>
<a
href="https://github.com/mindaugasw/json-deep-decoder"
target="_blank"
rel="noopener noreferrer"
>
About
</a>
<br>
<br>
</div>
<div id="input-container">
<textarea
id="json-input"
rows="8"
onkeydown="handleShortcut(event)"
></textarea>
<div class="d-grid col-12 col-md-6 col-lg-4 col-xl-3">
<button
type="button"
class="btn btn-outline-secondary"
onclick="decode()"
>
Decode
</button>
</div>
<br>
</div>
<div id="error-container" hidden class="alert alert-danger" role="alert">
A simple warning alert—check it out!
</div>
<div id="output-container"></div>
</div>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"
crossorigin="anonymous"
></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/json-formatter-js"></script>
<script>
const inputElement = document.getElementById('json-input');
const errorElement = document.getElementById('error-container');
const outputElement = document.getElementById('output-container');
let counter = 0;
let previousInputs = [];
function decode() {
const content = inputElement.value;
let parsedData;
try {
parsedData = deepDecode(content);
} catch (exception) {
errorElement.innerText = exception.message;
errorElement.hidden = false;
return;
}
errorElement.hidden = true;
previousInputs[counter] = parsedData;
outputElement.prepend(getDecodedValueElement(parsedData, counter));
switchFormat(counter, true);
counter++;
}
function deepDecode(content, throwException = true) {
let parsedData;
if (typeof content === 'string') {
try {
parsedData = JSON.parse(content);
} catch (exception) {
if (throwException) {
throw exception;
}
return content;
}
} else {
parsedData = content;
}
// For whatever reason when this is directly inside switch(), it doesn't work
const type = typeof parsedData;
switch (true) {
case parsedData === null:
return null;
case type === 'boolean':
case type === 'number':
case type === 'bigint':
return parsedData;
case type === 'string':
return parsedData === content
? parsedData
: deepDecode(parsedData, false);
case Array.isArray(parsedData) && parsedData.length === 0:
return [];
case type === 'object' && Object.keys(parsedData).length === 0:
return {};
}
let deepParsedData = Array.isArray(parsedData) ? [] : {};
for (const [key, value] of Object.entries(parsedData)) {
deepParsedData[key] = deepDecode(value, false);
}
return deepParsedData;
}
/**
* @param {any} parsedData
* @param {number} counter
* @returns {HTMLDivElement}
*/
function getDecodedValueElement(parsedData, counter) {
const summary = document.createElement('summary');
const datetimeText = new Intl.DateTimeFormat(
'lt-lt',
{
dateStyle: 'short',
timeStyle: 'medium',
}).format(new Date());
summary.innerHTML = `#${counter + 1} @ ${datetimeText} <span id="${getSwitchElementId(counter)}"></span>`;
const contentDiv = document.createElement('div');
contentDiv.id = getJsonContentElementId(counter);
const details = document.createElement('details');
details.open = true;
details.append(summary);
details.append(contentDiv)
const div = document.createElement('div');
div.append(details);
div.append(document.createElement('br'));
return div;
}
/**
* @param {number} index
* @param {boolean} pretty
*/
function switchFormat(index, pretty) {
const switchHtml =
`Switch to
<a
href="#"
onclick="switchFormat(${index}, ${!pretty})"
>${pretty ? 'plain text' : 'pretty'}</a>
format`;
const switchElement = document.getElementById(getSwitchElementId(index));
switchElement.innerHTML = switchHtml;
const jsonData = previousInputs[index];
let contentHtml;
if (pretty) {
const jsonFormatter = new JSONFormatter(jsonData, Infinity);
contentHtml = jsonFormatter.render();
} else {
contentHtml = document.createElement('pre');
contentHtml.innerText = JSON.stringify(jsonData, null, 2);
}
const contentElement = document.getElementById(getJsonContentElementId(index));
contentElement.replaceChildren(contentHtml);
}
/**
* @param {number} index
* @returns {string}
*/
function getSwitchElementId(index) {
return `switch-${index}`;
}
/**
* @param {number} index
* @returns {string}
*/
function getJsonContentElementId(index) {
return `json-content-${index}`;
}
/**
* @param {KeyboardEvent} event
*/
function handleShortcut(event) {
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
decode();
}
}
/**
* @param {boolean} print
*/
function runUnitTests(print = true) {
const configuration = [
{
input: 'null',
expected: null,
},
{
input: 'false',
expected: false,
},
{
input: 'true',
expected: true,
},
{
input: '0',
expected: 0,
},
{
input: '123',
expected: 123,
},
{
input: '""',
expected: '',
},
{
input: '"string"',
expected: 'string',
},
{
input: '[]',
expected: [],
},
{
input: '{}',
expected: {},
},
{
// Array with all data types
input: '[null, false, true, 0, 123, "0", "", "string", [], {}]',
expected: [null, false, true, 0, 123, 0, '', 'string', [], {}],
},
{
// Simple object
input: '{"a": "ok"}',
expected: {a: 'ok'},
},
{
// Simple JSON object as string
input: '"{\\"a\\": \\"ok\\"}"',
expected: {a: "ok"},
},
{
// Nested JSON object as string
input: '"{\\"b\\":\\"{\\\\\\"a\\\\\\":\\\\\\"ok\\\\\\"}\\"}"',
expected: {
b: {
a: "ok",
},
},
},
{
// Simple JSON array as string
input: '"[\\"a\\"]"',
expected: ['a'],
},
{
// Nested JSON array as string
input: '["[\\"a\\"]"]',
expected: [['a']],
},
];
let i = 0;
let errors = false;
for (const test of configuration) {
console.log(`#${i} input:`, test.input);
const actual = deepDecode(test.input);
if (_.isEqual(test.expected, actual)) {
console.log(`#${i} OK:`, actual);
} else {
errors = true;
console.error(`#${i} Expected:`, test.expected);
console.error(`#${i} Actual:`, actual);
}
if (print) {
inputElement.value = test.input;
decode();
}
i++;
}
if (errors) {
console.error('At least 1 test failed');
} else {
console.log('Tests completed successfully');
}
}
</script>
</body>
</html>