-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
88 lines (78 loc) · 2.47 KB
/
popup.js
File metadata and controls
88 lines (78 loc) · 2.47 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
document.addEventListener('DOMContentLoaded', function() {
// Get DOM elements
const inputJson = document.getElementById('input-json');
const outputJson = document.getElementById('output-json');
const convertBtn = document.getElementById('convert-btn');
const copyBtn = document.getElementById('copy-btn');
const pasteBtn = document.getElementById('paste-btn');
const errorMessage = document.getElementById('error-message');
// Convert camelCase/PascalCase to underscore_case
function toUnderscoreCase(str) {
return str
.replace(/([A-Z])/g, '_$1')
.replace(/^_/, '')
.toLowerCase();
}
// Process JSON object recursively
function processJsonObject(obj) {
if (Array.isArray(obj)) {
return obj.map(item => processJsonObject(item));
} else if (obj !== null && typeof obj === 'object') {
const newObj = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const newKey = toUnderscoreCase(key);
newObj[newKey] = processJsonObject(obj[key]);
}
}
return newObj;
}
return obj;
}
// Convert JSON
function convertJson() {
try {
errorMessage.classList.add('hidden');
const input = inputJson.value.trim();
if (!input) {
showError('Please enter some JSON to convert');
return;
}
const jsonObj = JSON.parse(input);
const convertedObj = processJsonObject(jsonObj);
outputJson.value = JSON.stringify(convertedObj, null, 2);
} catch (error) {
showError('Invalid JSON: ' + error.message);
}
}
// Show error message
function showError(message) {
errorMessage.textContent = message;
errorMessage.classList.remove('hidden');
}
// Copy to clipboard
function copyToClipboard() {
outputJson.select();
document.execCommand('copy');
// Visual feedback
const originalText = copyBtn.textContent;
copyBtn.textContent = 'Copied!';
setTimeout(() => {
copyBtn.textContent = originalText;
}, 1500);
}
// Paste from clipboard
function pasteFromClipboard() {
navigator.clipboard.readText()
.then(text => {
inputJson.value = text;
})
.catch(err => {
showError('Failed to read clipboard: ' + err);
});
}
// Event listeners
convertBtn.addEventListener('click', convertJson);
copyBtn.addEventListener('click', copyToClipboard);
pasteBtn.addEventListener('click', pasteFromClipboard);
});