-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv-to-json.html
More file actions
258 lines (232 loc) · 10.3 KB
/
csv-to-json.html
File metadata and controls
258 lines (232 loc) · 10.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSV to JSON</title>
<link rel="stylesheet" href="common.css">
<style>
body { display: flex; flex-direction: column; }
.options { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; }
.option-group input[type="text"] { width: 50px; text-align: center; font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace; }
.stats { font-size: 0.85rem; color: var(--text-secondary); margin-left: auto; }
</style>
</head>
<body>
<a href="index.html" class="back-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M19 12H5M12 19l-7-7 7-7"/>
</svg>
All Tools
</a>
<header>
<h1>CSV to JSON</h1>
<p class="subtitle">Convert CSV data to JSON format</p>
</header>
<div class="controls">
<button id="convertBtn">Convert</button>
<button id="clearBtn" class="secondary">Clear</button>
<div class="options">
<div class="option-group">
<label for="delimiterInput">Delimiter:</label>
<input type="text" id="delimiterInput" value="," maxlength="1">
</div>
<div class="option-group">
<input type="checkbox" id="hasHeader" checked>
<label for="hasHeader">First row is header</label>
</div>
<div class="option-group">
<input type="checkbox" id="trimValues" checked>
<label for="trimValues">Trim whitespace</label>
</div>
<span id="stats" class="stats"></span>
</div>
</div>
<div class="container">
<div class="pane">
<div class="pane-header">
<span class="label">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
</svg>
CSV Input
<span id="statusIndicator" class="status-indicator"></span>
</span>
</div>
<textarea id="csvInput" placeholder='Paste your CSV data here...
Example:
name,age,city
John,30,New York
Jane,25,Los Angeles
Bob,35,Chicago' spellcheck="false"></textarea>
<div id="errorMessage" class="error-message"></div>
</div>
<div class="pane">
<div class="pane-header">
<span class="label">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
</svg>
JSON Output
</span>
<button id="copyBtn" class="copy-btn">Copy</button>
</div>
<textarea id="jsonOutput" readonly placeholder="JSON output will appear here..." spellcheck="false"></textarea>
</div>
</div>
<script>
const csvInput = document.getElementById('csvInput');
const jsonOutput = document.getElementById('jsonOutput');
const delimiterInput = document.getElementById('delimiterInput');
const hasHeaderCheckbox = document.getElementById('hasHeader');
const trimValuesCheckbox = document.getElementById('trimValues');
const convertBtn = document.getElementById('convertBtn');
const clearBtn = document.getElementById('clearBtn');
const copyBtn = document.getElementById('copyBtn');
const errorMessage = document.getElementById('errorMessage');
const statusIndicator = document.getElementById('statusIndicator');
const stats = document.getElementById('stats');
function parseCSV(csv, delimiter, trimValues) {
const rows = [];
let currentRow = [];
let currentField = '';
let inQuotes = false;
for (let i = 0; i < csv.length; i++) {
const char = csv[i];
const nextChar = csv[i + 1];
if (inQuotes) {
if (char === '"') {
if (nextChar === '"') {
// Escaped quote
currentField += '"';
i++;
} else {
// End of quoted field
inQuotes = false;
}
} else {
currentField += char;
}
} else {
if (char === '"') {
inQuotes = true;
} else if (char === delimiter) {
currentRow.push(trimValues ? currentField.trim() : currentField);
currentField = '';
} else if (char === '\n' || (char === '\r' && nextChar === '\n')) {
currentRow.push(trimValues ? currentField.trim() : currentField);
if (currentRow.length > 0 && currentRow.some(f => f !== '')) {
rows.push(currentRow);
}
currentRow = [];
currentField = '';
if (char === '\r') i++; // Skip \n in \r\n
} else if (char !== '\r') {
currentField += char;
}
}
}
// Don't forget the last field/row
currentRow.push(trimValues ? currentField.trim() : currentField);
if (currentRow.length > 0 && currentRow.some(f => f !== '')) {
rows.push(currentRow);
}
return rows;
}
function convert() {
const csv = csvInput.value;
const delimiter = delimiterInput.value || ',';
const hasHeader = hasHeaderCheckbox.checked;
const trimValues = trimValuesCheckbox.checked;
errorMessage.style.display = 'none';
statusIndicator.className = 'status-indicator';
stats.textContent = '';
if (!csv.trim()) {
jsonOutput.value = '';
return;
}
try {
const rows = parseCSV(csv, delimiter, trimValues);
if (rows.length === 0) {
jsonOutput.value = '[]';
statusIndicator.className = 'status-indicator valid';
return;
}
let result;
let rowCount;
if (hasHeader) {
const headers = rows[0];
const dataRows = rows.slice(1);
rowCount = dataRows.length;
result = dataRows.map(row => {
const obj = {};
headers.forEach((header, i) => {
let value = row[i] !== undefined ? row[i] : '';
// Try to parse numbers and booleans
if (value === 'true') value = true;
else if (value === 'false') value = false;
else if (value === 'null') value = null;
else if (value !== '' && !isNaN(value) && !isNaN(parseFloat(value))) {
value = parseFloat(value);
}
obj[header] = value;
});
return obj;
});
} else {
rowCount = rows.length;
result = rows.map(row => {
return row.map(value => {
if (value === 'true') return true;
if (value === 'false') return false;
if (value === 'null') return null;
if (value !== '' && !isNaN(value) && !isNaN(parseFloat(value))) {
return parseFloat(value);
}
return value;
});
});
}
jsonOutput.value = JSON.stringify(result, null, 2);
statusIndicator.className = 'status-indicator valid';
stats.textContent = `${rowCount} rows, ${rows[0]?.length || 0} columns`;
} catch (e) {
errorMessage.style.display = 'block';
errorMessage.textContent = 'Error parsing CSV: ' + e.message;
jsonOutput.value = '';
statusIndicator.className = 'status-indicator invalid';
}
}
convertBtn.addEventListener('click', convert);
// Auto-convert on input
csvInput.addEventListener('input', convert);
delimiterInput.addEventListener('input', convert);
hasHeaderCheckbox.addEventListener('change', convert);
trimValuesCheckbox.addEventListener('change', convert);
clearBtn.addEventListener('click', () => {
csvInput.value = '';
jsonOutput.value = '';
errorMessage.style.display = 'none';
statusIndicator.className = 'status-indicator';
stats.textContent = '';
csvInput.focus();
});
copyBtn.addEventListener('click', () => {
if (!jsonOutput.value) return;
navigator.clipboard.writeText(jsonOutput.value).then(() => {
const originalText = copyBtn.textContent;
copyBtn.textContent = 'Copied!';
copyBtn.classList.add('copied');
setTimeout(() => {
copyBtn.textContent = originalText;
copyBtn.classList.remove('copied');
}, 2000);
});
});
</script>
</body>
</html>