vue解析上传的json文件信息

发布时间 2023-12-07 20:57:30作者: SKa-M

1.模版

<a-upload
      name="layoutFile"
      v-model:file-list="fileList"
      @change="importModules"
      accept="*"
      :showUploadList="false"
      :customRequest="() => {}"
      :headers="reqHeader"
    >
      <a-button v-if="value === '导入项目'" class="tab_list_btn" type="primary" size="small"
        >导入项目
        <template #icon>
          <PlusOutlined />
        </template>
      </a-button>
    </a-upload>

2.事件
importModules(e: any) {
  this.fileInfo = e?.file?.originFileObj;
  if (this.fileInfo) {
    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e?.target?.result;
      try {
        const parsedData = JSON.parse(content);
        const jsonData = JSON.parse(JSON.stringify(parsedData, null, 2));
        console.log('jsonData', jsonData); // 解析后的对象
      } catch (error) {
        console.error('Error parsing JSON file:', error);
      }
    };

    reader.readAsText(this.fileInfo);
  }
  message.success('上传成功');
}