-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcsv-json-converter.html
More file actions
441 lines (389 loc) · 19.2 KB
/
csv-json-converter.html
File metadata and controls
441 lines (389 loc) · 19.2 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="images/logo.png">
<link rel="apple-touch-icon" href="images/logo.png">
<title>CSV ⇄ JSON Converter - Developer Toolkit | DevDunia</title>
<meta name="description" content="Convert between CSV and JSON formats with proper syntax. Free online CSV to JSON and JSON to CSV converter tool for developers.">
<script src="https://cdn.tailwindcss.com"></script>
<script src="js/common.js"></script>
<style>
body {
background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
}
</style>
</head>
<body class="h-screen lg:ml-72">
<!-- Background: Consistent Subtle Dark Gradient -->
<div class="fixed inset-0 -z-10 bg-gradient-to-br from-gray-900 via-slate-900 to-gray-900"></div>
<!-- Main Container -->
<div class="main-content">
<div class="relative z-10 container mx-auto px-4 pt-16 pb-24 sm:px-6 lg:px-8">
<!-- Page Header -->
<div class="text-center mb-12">
<h1 class="text-3xl sm:text-4xl font-bold mb-4 tracking-tight
text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-cyan-500">
CSV ⇄ JSON Converter
</h1>
<p class="text-lg text-gray-400 max-w-2xl mx-auto">
Convert between CSV and JSON formats with proper syntax and formatting.
</p>
</div>
<!-- Tool Container -->
<div class="max-w-6xl mx-auto">
<div class="bg-slate-800/70 backdrop-blur-md rounded-lg shadow-lg border border-slate-700/60 p-6">
<!-- Conversion Direction -->
<div class="mb-6">
<div class="flex items-center justify-center space-x-4">
<button id="csv-to-json-btn" class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-200 flex items-center space-x-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
</svg>
<span>CSV → JSON</span>
</button>
<button id="json-to-csv-btn" class="px-6 py-3 bg-slate-600 hover:bg-slate-700 text-white font-medium rounded-lg transition-colors duration-200 flex items-center space-x-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
</svg>
<span>JSON → CSV</span>
</button>
</div>
</div>
<!-- Input Section -->
<div class="mb-6">
<label id="input-label" for="input-text" class="block text-sm font-medium text-gray-300 mb-2">
CSV Input
</label>
<textarea
id="input-text"
rows="10"
class="w-full px-4 py-3 bg-slate-700/50 border border-slate-600 rounded-lg text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none font-mono text-sm"
placeholder="Paste your CSV data here..."
></textarea>
</div>
<!-- Options Section -->
<div class="mb-6">
<h3 class="text-sm font-medium text-gray-300 mb-3">Conversion Options</h3>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label class="flex items-center text-gray-400">
<input type="checkbox" id="include-headers" class="mr-2" checked>
<span class="text-sm">Include Headers</span>
</label>
</div>
<div>
<label class="flex items-center text-gray-400">
<input type="checkbox" id="pretty-format" class="mr-2">
<span class="text-sm">Pretty Format JSON</span>
</label>
</div>
<div>
<label class="flex items-center text-gray-400">
<input type="checkbox" id="trim-whitespace" class="mr-2" checked>
<span class="text-sm">Trim Whitespace</span>
</label>
</div>
</div>
</div>
<!-- Action Buttons -->
<div class="flex flex-wrap gap-3 mb-6">
<button id="convert-btn" class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-200 flex items-center space-x-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
</svg>
<span>Convert</span>
</button>
<button class="clear-btn px-6 py-3 bg-slate-600 hover:bg-slate-700 text-white font-medium rounded-lg transition-colors duration-200 flex items-center space-x-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
</svg>
<span>Clear All</span>
</button>
</div>
<!-- Error Display -->
<div id="error-display" class="hidden mb-6 p-4 bg-red-900/50 border border-red-600/50 rounded-lg">
<div class="flex items-center space-x-2">
<svg class="w-5 h-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<span id="error-message" class="text-red-300"></span>
</div>
</div>
<!-- Output Section -->
<div id="output-section" class="hidden">
<label id="output-label" for="output-text" class="block text-sm font-medium text-gray-300 mb-2">
JSON Output
</label>
<div class="relative">
<textarea
id="output-text"
rows="12"
class="w-full px-4 py-3 bg-slate-700/50 border border-slate-600 rounded-lg text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none font-mono text-sm"
readonly
></textarea>
<!-- Copy Button -->
<button class="copy-btn absolute top-2 right-2 px-3 py-1 bg-slate-600 hover:bg-slate-700 text-white text-sm rounded transition-colors duration-200 flex items-center space-x-1" data-target="output-text">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
</div>
<!-- Examples Section -->
<div class="mt-8 p-4 bg-slate-700/30 rounded-lg border border-slate-600/50">
<h3 class="text-lg font-semibold text-blue-400 mb-3">Conversion Examples</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
<div>
<p class="text-gray-300 font-medium mb-2">CSV Input:</p>
<pre class="text-gray-400 text-xs bg-slate-800/50 p-2 rounded">name,age,city
John,30,New York
Jane,25,Los Angeles
Bob,35,Chicago</pre>
<p class="text-gray-500 text-xs mt-1">→ JSON array of objects</p>
</div>
<div>
<p class="text-gray-300 font-medium mb-2">JSON Output:</p>
<pre class="text-gray-400 text-xs bg-slate-800/50 p-2 rounded">[
{
"name": "John",
"age": "30",
"city": "New York"
},
{
"name": "Jane",
"age": "25",
"city": "Los Angeles"
}
]</pre>
<p class="text-gray-500 text-xs mt-1">→ Structured data format</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer include -->
<div id="footer"></div>
<script>
fetch("footer.html")
.then(response => response.text())
.then(data => {
document.getElementById("footer").innerHTML = data;
})
.catch(err => console.error("Failed to load footer:", err));
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const inputText = document.getElementById('input-text');
const outputText = document.getElementById('output-text');
const convertBtn = document.getElementById('convert-btn');
const outputSection = document.getElementById('output-section');
const errorDisplay = document.getElementById('error-display');
const errorMessage = document.getElementById('error-message');
const inputLabel = document.getElementById('input-label');
const outputLabel = document.getElementById('output-label');
const csvToJsonBtn = document.getElementById('csv-to-json-btn');
const jsonToCsvBtn = document.getElementById('json-to-csv-btn');
let conversionMode = 'csv-to-json'; // Default mode
// Mode switching
csvToJsonBtn.addEventListener('click', function() {
conversionMode = 'csv-to-json';
updateUI();
csvToJsonBtn.classList.remove('bg-slate-600');
csvToJsonBtn.classList.add('bg-blue-600');
jsonToCsvBtn.classList.remove('bg-blue-600');
jsonToCsvBtn.classList.add('bg-slate-600');
});
jsonToCsvBtn.addEventListener('click', function() {
conversionMode = 'json-to-csv';
updateUI();
jsonToCsvBtn.classList.remove('bg-slate-600');
jsonToCsvBtn.classList.add('bg-blue-600');
csvToJsonBtn.classList.remove('bg-blue-600');
csvToJsonBtn.classList.add('bg-slate-600');
});
function updateUI() {
if (conversionMode === 'csv-to-json') {
inputLabel.textContent = 'CSV Input';
outputLabel.textContent = 'JSON Output';
inputText.placeholder = 'Paste your CSV data here...';
} else {
inputLabel.textContent = 'JSON Input';
outputLabel.textContent = 'CSV Output';
inputText.placeholder = 'Paste your JSON data here...';
}
hideOutput();
hideError();
}
// Convert
convertBtn.addEventListener('click', function() {
const input = inputText.value.trim();
if (!input) {
showError('Please enter some data to convert');
return;
}
try {
let result;
if (conversionMode === 'csv-to-json') {
result = csvToJson(input);
} else {
result = jsonToCsv(input);
}
outputText.value = result;
showOutput();
hideError();
} catch (error) {
showError('Conversion failed: ' + error.message);
hideOutput();
}
});
// Helper functions
function showOutput() {
outputSection.classList.remove('hidden');
}
function hideOutput() {
outputSection.classList.add('hidden');
}
function showError(message) {
errorMessage.textContent = message;
errorDisplay.classList.remove('hidden');
}
function hideError() {
errorDisplay.classList.add('hidden');
}
// CSV to JSON conversion
function csvToJson(csvString) {
const lines = csvString.split('\n').filter(line => line.trim());
if (lines.length === 0) {
throw new Error('No data found');
}
const includeHeaders = document.getElementById('include-headers').checked;
const prettyFormat = document.getElementById('pretty-format').checked;
const trimWhitespace = document.getElementById('trim-whitespace').checked;
// Parse CSV
const rows = lines.map(line => parseCSVLine(line, trimWhitespace));
if (includeHeaders && rows.length > 0) {
const headers = rows[0];
const data = rows.slice(1).map(row => {
const obj = {};
headers.forEach((header, index) => {
obj[header] = row[index] || '';
});
return obj;
});
return prettyFormat ? JSON.stringify(data, null, 2) : JSON.stringify(data);
} else {
return prettyFormat ? JSON.stringify(rows, null, 2) : JSON.stringify(rows);
}
}
// JSON to CSV conversion
function jsonToCsv(jsonString) {
const includeHeaders = document.getElementById('include-headers').checked;
const trimWhitespace = document.getElementById('trim-whitespace').checked;
let data;
try {
data = JSON.parse(jsonString);
} catch (error) {
throw new Error('Invalid JSON format');
}
if (!Array.isArray(data)) {
throw new Error('JSON must be an array of objects');
}
if (data.length === 0) {
return '';
}
// Get all unique keys
const allKeys = new Set();
data.forEach(item => {
if (typeof item === 'object' && item !== null) {
Object.keys(item).forEach(key => allKeys.add(key));
}
});
const headers = Array.from(allKeys);
const rows = [];
// Add headers if requested
if (includeHeaders) {
rows.push(headers);
}
// Add data rows
data.forEach(item => {
if (typeof item === 'object' && item !== null) {
const row = headers.map(header => {
const value = item[header] || '';
return escapeCSVValue(value.toString());
});
rows.push(row);
}
});
return rows.map(row => row.join(',')).join('\n');
}
// Parse a single CSV line
function parseCSVLine(line, trimWhitespace) {
const result = [];
let current = '';
let inQuotes = false;
let i = 0;
while (i < line.length) {
const char = line[i];
if (char === '"') {
if (inQuotes && line[i + 1] === '"') {
// Escaped quote
current += '"';
i += 2;
} else {
// Toggle quote state
inQuotes = !inQuotes;
i++;
}
} else if (char === ',' && !inQuotes) {
// Field separator
result.push(trimWhitespace ? current.trim() : current);
current = '';
i++;
} else {
current += char;
i++;
}
}
// Add the last field
result.push(trimWhitespace ? current.trim() : current);
return result;
}
// Escape CSV value
function escapeCSVValue(value) {
if (value.includes(',') || value.includes('"') || value.includes('\n')) {
return '"' + value.replace(/"/g, '""') + '"';
}
return value;
}
// Example on page load
window.addEventListener('load', () => {
const exampleCSV = `name,age,city,email
John Doe,30,New York,john@example.com
Jane Smith,25,Los Angeles,jane@example.com
Bob Johnson,35,Chicago,bob@example.com`;
inputText.value = exampleCSV;
});
});
</script>
</div>
</div>
<!-- Sidebar Scripts -->
<!-- Include Final Sidebar -->
<div id="sidebar-container"></div>
<script>
// Load final_sidebar.html content
fetch('final_sidebar.html')
.then(response => response.text())
.then(html => {
document.getElementById('sidebar-container').innerHTML = html;
})
.catch(error => {
console.error('Error loading sidebar:', error);
});
</script>
</body>
</html>