FileSaver.js导出json文件和文本

  最近刚刚写了个json数据导出生成Excel文件的,顺便总结下利用FileSaver.js导出其他文件的,这里要注意的一个点就是,当导出的是json文件或是txt文件时,导出的内容要是字符串,特别当时导出的数据是json数据时,要记得转一把。好了,不多说,直接上一个小小的demo,如下:

 

下载地址:

 

https://github.com/eligrey/FileSaver.js

 

 

 1 <!DOCTYPE html>
 2 <html>
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>导出生成json文件和文本</title>
 7     <script src="js/FileSaver.min.js"></script>
 8 </head>
 9 
10 <body>
11 <button onclick="downloadJson(students)">导出生成json文件</button>
12 <button onclick="downloadText(students)">导出生成文本</button>
13 </body>
14 <script>
15     var students = [{
16         "name": "小明1",
17         "age": "6",
18         "sex": "",
19         "height": "60"
20     }, {
21         "name": "小明2",
22         "age": "7",
23         "sex": "",
24         "height": "70"
25     }, {
26         "name": "小明3",
27         "age": "8",
28         "sex": "",
29         "height": "80"
30     }];
31     // 导出生成json文件
32     function downloadJson(data) {
33         var blob = new Blob([JSON.stringify(data)], { type: "" });
34         saveAs(blob, "hello.json");
35     }
36     // 导出生成文本
37     function downloadText(data) {
38         var blob = new Blob([JSON.stringify(data)], { type: "text/plain;charset=utf-8" });
39         saveAs(blob, "hello.txt");
40     }
41 
42 </script>
43 
44 </html>

 

posted @ 2017-12-25 22:32  绝对小孩  阅读(13069)  评论(1编辑  收藏  举报