-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathjson-csv-table-viewer.html
More file actions
82 lines (72 loc) · 2.74 KB
/
json-csv-table-viewer.html
File metadata and controls
82 lines (72 loc) · 2.74 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
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="/logo.svg">
<title>JSON/CSV Table Data Viewer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.err { color: red; }
table { border-collapse: collapse; }
table, th, td { border: 1px solid black; }
textarea {
width: 100%;
max-width: 700px;
}
</style>
</head>
<body>
<script type="module">
import van from "./van-latest.min.js"
const {button, input, div, label, p, pre, table, tbody, td, textarea, th, thead, tr} = van.tags
const TableViewer = ({inputText, inputType}) => {
const jsonRadioDom = input({type: "radio", checked: inputType === "json",
name: "inputType", value: "json"})
const csvRadioDom = input({type: "radio", checked: inputType === "csv",
name: "inputType", value: "csv"})
const autoGrow = e => {
e.style.height = "5px"
e.style.height = (e.scrollHeight + 5) + "px"
}
const textareaDom = textarea({oninput: e => autoGrow(e.target)}, inputText)
setTimeout(() => autoGrow(textareaDom), 10)
const text = van.state("")
const tableFromJson = text => {
const json = JSON.parse(text), head = Object.keys(json[0])
return {
head,
data: json.map(row => head.map(h => row[h]))
}
}
const tableFromCsv = text => {
const lines = text.split("\n").filter(l => l.length > 0)
return {
head: lines[0].split(","),
data: lines.slice(1).map(l => l.split(",")),
}
}
return div(
div(jsonRadioDom, label("JSON"), csvRadioDom, label("CSV (Quoting not Supported)")),
div(textareaDom),
div(button({onclick: () => text.val = textareaDom.value}, "Show Table")),
p(() => {
if (!text.val) return div()
try {
const {head, data} = (jsonRadioDom.checked ? tableFromJson : tableFromCsv)(text.val)
return table(
thead(tr(head.map(h => th(h)))),
tbody(data.map(row => tr(row.map(col => td(col))))),
)
} catch (e) {
return pre({class: "err"}, e.toString())
}
}),
)
}
van.add(document.body, TableViewer({
inputText: `[{"id":1,"name":"John Doe","email":"john.doe@example.com","age":35,"country":"USA"},{"id":2,"name":"Jane Smith","email":"jane.smith@example.com","age":28,"country":"Canada"},{"id":3,"name":"Bob Johnson","email":"bob.johnson@example.com","age":42,"country":"Australia"}]`,
inputType: "json",
}))
</script>
</body>
</html>