-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
77 lines (70 loc) · 2.67 KB
/
parser.js
File metadata and controls
77 lines (70 loc) · 2.67 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
document.getElementById('jsonFileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = JSON.parse(e.target.result);
if (data.A === undefined || data.B === undefined) {
alert('Fields A and B are required.');
return;
}
if (data.A === data.B) {
alert('Fields A and B are the same.');
} else if (data.B > data.A) {
alert('Field B is greater than A.');
} else {
alert('Fields A and B are different.');
}
} catch (err) {
alert('Invalid JSON file.');
}
};
reader.readAsText(file);
});
document.getElementById('jsonFileInput').setAttribute('accept', '.json,.xml,.yaml,.yml');
function parseFileContent(content, fileType) {
if (fileType === 'json') {
return JSON.parse(content);
} else if (fileType === 'xml') {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(content, 'application/xml');
const A = xmlDoc.getElementsByTagName('A')[0]?.textContent;
const B = xmlDoc.getElementsByTagName('B')[0]?.textContent;
return { A, B };
} else if (fileType === 'yaml' || fileType === 'yml') {
// Requires js-yaml library
return jsyaml.load(content);
}
throw new Error('Unsupported file type');
}
document.getElementById('jsonFileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const ext = file.name.split('.').pop().toLowerCase();
let fileType;
if (ext === 'json') fileType = 'json';
else if (ext === 'xml') fileType = 'xml';
else if (ext === 'yaml' || ext === 'yml') fileType = 'yaml';
else throw new Error('Unsupported file type');
const data = parseFileContent(e.target.result, fileType);
if (data.A === undefined || data.B === undefined) {
alert('Fields A and B are required.');
return;
}
if (data.A === data.B) {
alert('Fields A and B are the same.');
} else if (data.B > data.A) {
alert('Field B is greater than A.');
} else {
alert('Fields A and B are different.');
}
} catch (err) {
alert('Invalid file or format.');
}
};
reader.readAsText(file);
});