Men的博客

欢迎光临!

0%

CSV to YAML

目前研究将文档中的数据转位yaml,如下

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
<body>
<input type="file" id="datafile">
</body>
<script>
function readInputFile(event) {
let file = event.target.files[0];
if (!file) {
return;
}
transCSVFileToYaml(file)
}
function transCSVFileToYaml(file) {
var out = '';
const reader = new FileReader();
reader.readAsText(file);
reader.onload = function () {
let dataStr = reader.result;
let rows = dataStr.split('\n');
out += " Object:\n"
out += " type: object\n"
out += " description: ''\n"
out += " properties:\n"

for (var i = 0; i < rows.length; i++) {
const columns = rows[i].split(',');
if (columns.length < 3) {
continue;
}
const obj = columns[0].trim();
const type = columns[1].trim();
const desc = columns[2].trim();
out += " " + obj + ':\n';
if (type == 'object') {
out += " description: '" + desc + "'\n";
out += " $ref: '#/components/schemas/" + obj + "'\n";
}else if (type == 'object[]') {
out += " description: '" + desc + "'\n";
out += ' type: array' + '\n';
out += " items:" + "\n";
out += " $ref: '#/components/schemas/" + obj + "'\n"
}else if (type == 'string[]') {
out += " description: '" + desc + "'\n";
out += ' type: array' + '\n';
out += " items:" + "\n";
out += " type: string" + "'\n"

}else if (type == 'number[]') {
out += " description: '" + desc + "'\n";
out += ' type: array' + '\n';
out += " items:" + "\n";
out += " type: number" + "'\n"

}else {
out += ' type: ' + type + '\n';
out += " description: '" + desc + "'\n";
}
}
console.log(out);
// downloadFile(out);
}

}
function downloadFile(content) {
// 它适用于所有支持 HTML5 的浏览器,因为它使用了 元素的下载属性:
const element = document.createElement("a");
// Blob 是一种可以存储二进制数据的数据类型
// 根据要保存的文件,它可以有不同的值
const blob = new Blob([content], { type: "plain/text" });
// createObjectURL() 静态方法创建一个 DOMString,其中包含一个 URL,该 URL 表示参数中给定的对象。
const fileUrl = URL.createObjectURL(blob);
// setAttribute() 设置指定元素的属性值。
element.setAttribute("href", fileUrl); // 文件位置
element.setAttribute("download", "txt.yaml"); // 文件名
element.style.display = "none";
// 使用 appendChild() 方法将一个节点附加到指定父节点的子节点列表的末尾处
document.body.appendChild(element);
element.click();
// Node 接口的 removeChild() 方法从 DOM 中移除一个子节点并返回移除的节点
document.body.removeChild(element);
}
document.getElementById('datafile').addEventListener('change', readInputFile, false);
</script>