js将xlsx/xls 转为json

  1. 把 xlsx/xls 转换为 csv
    将文件另存为csv文件

  2. 把 csv 转换为 json
    可以在 VS Code 里安装 JSON to CSV插件实现格式转换:

首先打开 VS Code
搜索插件 JSON to CSV 并安装
把 csv 文件拖拽到 VS Code
按 Ctrl + Shift + P 打开命令面板
输入命令:Convert CSV to JSON 并回车
此时已转换为 JSON 格式了,但只是一维数组格式的 JSON。

  1. 把一维数组结构转换为树形结构
    定义一个函数,把step2的 JSON 数据作为参数传递进此函数,将返回一个树形结构的 JS 对象:
function listToTree(list) {
    
    
  let tree = {
    
    
    label: 'root',
    value: '',
    level: 0,
    children: [],
  }
  let currParent = tree

  list.forEach((item) => {
    
    
    ;[
      ['一级'],
      ['二级'],
      ['三级'], // 表格的标题
    ].forEach(([item], index) => {
    
    
      const label= item[item]
      const value= item[item]
      const level = index + 1

      if (label) {
    
    
        let node = {
    
    }
        node.label= label
        node.value = value
        node.level = level

        while (currParent.level >= level) {
    
    
          currParent = currParent.parent
        }

        let children = currParent.children
        if (!children) {
    
    
          children = currParent.children = []
        }

        node.parent = currParent
        children.push(node)
        currParent = node
      }
    })
  })

  return tree
}
  1. 把树形结构 JS 对象转换为 JSON 字符串
function treeToJson(tree) {
    
    
  function recurse(children) {
    
    
    return children.map((item) => {
    
    
      const node = {
    
    
        label: item.label,
        value: item.value,
      }
      if (item.children) {
    
    
        node.children = recurse(item.children)
      }
      return node
    })
  }
  return JSON.stringify(recurse(tree.children))
}

猜你喜欢

转载自blog.csdn.net/qq_43585322/article/details/129245557