vue 处理JSON文件——上传导入、下载导出、在线预览

简介: vue 处理JSON文件——上传导入、下载导出、在线预览

上传导入JSON文件

<el-button @click="importData" size="mini">导入</el-button>
 
  data() {
    return {
      fileList: [],
      uploadData: [],
      dialogImport: false,
importData() {
      this.dialogImport = true;
    },
 
   <el-dialog
      :visible.sync="dialogImport"
      title="导入"
      v-if="dialogImport"
      width="40%"
      append-to-body
    >
      <div style="text-align:center">
        <!-- 此处action需为有效的任意接口——当前为官网范例接口 -->
        <el-upload
          drag
          :limit="1"
          action="https://jsonplaceholder.typicode.com/posts/"
          ref="upload"
          accept=".json"
          :file-list="fileList"
          :on-success="onSuccess"
          :on-remove="onRemove"
          :on-exceed="handleExceed"
          :on-preview="handlePreview"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            上传json文件,且只能上传 1 个文件
          </div>
        </el-upload>
      </div>
      <span slot="footer">
        <el-button @click="dialogImport = false" size="mini">取 消</el-button>
        <el-button @click="importConfirm" size="mini" type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    // 上传文件超出文件数量限制/文件格式不符合要求时
    handleExceed(files, fileList) {
      this.$message.warning(`每次只能导入一个json文件!`);
    },

    // 文件上传成功
    onSuccess(res, file, fileList) {
      let reader = new FileReader();
      reader.readAsText(file.raw);
      reader.onload = (e) => {
        this.uploadData = [];
        this.uploadData = JSON.parse(e.target.result);
      };
    },

    // 移除文件
    onRemove(file) {
      this.fileList = [];
    },

    // 导入确认
    importConfirm() {
      this.$confirm("导入后原数据会被覆盖,确定导入吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
      // 使用目标数据变量接收上传后的文件数据
        this.stockData = this.uploadData;

        this.dialogImport = false;

        this.$message({
          type: "success",
          message: "导入成功!",
        });
      });
    },

在线预览JSON文件

续上例,上传文件后,点击文件名打开预览弹窗

jsonData: null,
      dialogPreviewJSON: false,
 
    handlePreview(file) {
      let reader = new FileReader();
      reader.readAsText(file.raw);
      reader.onload = (e) => {
        this.jsonData = JSON.parse(e.target.result);
        this.dialogPreviewJSON = true;
      };
    },
    <el-dialog
      :visible.sync="dialogPreviewJSON"
      title="JSON文件预览"
      v-if="dialogPreviewJSON"
      width="40%"
      append-to-body
    >
      <s-json :json="jsonData"></s-json>
    </el-dialog>

s-json.vue组件

<template>
  <div>
    <pre v-html="formattedJSON"></pre>
  </div>
</template>
<script>
export default {
  props: {
    json: Object,
  },
  mounted() {
    this.formattedJSON = syntaxHighlight(this.json);
  },
  data() {
    return {
      formattedJSON: "",
    };
  },
};

function syntaxHighlight(json) {
  if (typeof json != "string") {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json
    .replace(/&/g, "&")
    .replace(/</g, "<")
    .replace(/>/g, ">");
  return json.replace(
    /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
    function(match) {
      var cls = "number";
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = "key";
        } else {
          cls = "string";
        }
      } else if (/true|false/.test(match)) {
        cls = "boolean";
      } else if (/null/.test(match)) {
        cls = "null";
      }
      return '<span class="' + cls + '">' + match + "</span>";
    }
  );
}
</script>
<style scoped>
/deep/ pre {
  outline: 1px solid #ccc;
  padding: 5px;
  margin: 5px;
}

/deep/ .string {
  color: green;
}

/deep/ .number {
  color: darkorange;
}

/deep/ .boolean {
  color: blue;
}

/deep/ .null {
  color: magenta;
}

/deep/ .key {
  color: red;
}
</style>

下载导出JSON文件

会下载到浏览器默认的下载位置,无法统一指定下载的路径。

需安装插件 file-saver

npm install file-saver --save

vue文件中

// 插件 -- 下载文件
import FileSaver from "file-saver";
 
<el-button @click="exportData" size="mini">导出</el-button>
 
    exportData() {
      let data = JSON.stringify(this.stockData);
      let blob = new Blob([data], { type: "application/json" });
      FileSaver.saveAs(blob, `股票数据.json`);
    },
目录
相关文章
|
2天前
|
JSON JavaScript 数据格式
vue 格式化展示json(含彩色样式)
vue 格式化展示json(含彩色样式)
5 1
|
16天前
|
JSON 数据格式
Notepad++怎么格式化json文件?
Notepad++怎么格式化json文件?
15 3
|
15天前
|
JSON JavaScript 前端开发
jQuery获取json文件的方法
jQuery获取json文件的方法
13 2
|
14小时前
|
内存技术
文本,wangEditor下载失败,nvm降级到17.0.0,可能是,如果之前下载了4现在pack.json删除,再重新下
文本,wangEditor下载失败,nvm降级到17.0.0,可能是,如果之前下载了4现在pack.json删除,再重新下
|
14小时前
|
JSON 数据格式
Content type ‘text/plain;charset=UTF-8‘ not supported,这里要把测试文件转为json格式
Content type ‘text/plain;charset=UTF-8‘ not supported,这里要把测试文件转为json格式
|
2天前
|
JSON JavaScript 数据格式
vue 电子表格Excel的上传导入、导出下载、读取本地Excel、json转Excel
vue 电子表格Excel的上传导入、导出下载、读取本地Excel、json转Excel
7 0
|
3天前
|
JSON JavaScript 前端开发
一篇文章讲明白json文件格式详解
一篇文章讲明白json文件格式详解
|
15天前
|
存储 JSON JavaScript
【chat-gpt问答记录】python将数据存为json格式和yaml格式
【chat-gpt问答记录】python将数据存为json格式和yaml格式
27 1
|
3天前
|
存储 JSON JavaScript
使用JSONObject解析与生成JSON数据
使用JSONObject解析与生成JSON数据
|
3天前
|
JSON 前端开发 JavaScript
Go怎么解析不定JSON数据?
在Go中处理不确定结构的JSON数据,可以使用`map[string]interface{}`来解析,它能适应各种JSON键值对,但需要类型检查。另一种方法是使用`json.RawMessage`保存原始JSON,之后按需解析。此外,`json.Number`用于处理任意精度的数字。当JSON字段类型未知时,可以先解码到`interface{}`并做类型断言。第三方库如gjson和jsonparser提供更灵活的解析选项。