Node.js读取JSON数组文件解析及表格数据转换问题咨询
问题排查与解决方案
代码中的核心问题
fs.readFileSync使用错误:这是同步API,不接受回调函数,你传入的回调不会被执行。同步方法直接返回文件内容,若未指定编码,返回的是Buffer,必须转成字符串后才能解析JSON。- 数组方法拼写错误+使用不当:
foreach是拼写错误,正确写法是forEach;但forEach没有返回值,无法生成rows数组,应该用map方法来生成新数组。 - 对象键名大小写不匹配:你的JSON数据里年龄的键是
Age(大写A),但代码里用row.age(小写a),会导致取值为undefined。
修正后的完整代码
同步读取版本
const fs = require('fs'); // 同步读取文件,指定utf8编码直接获取字符串 const fileContent = fs.readFileSync("/Users/mken/Desktop/Node JS/DATA-TABLE/public/files/data.json", 'utf8'); // 解析JSON字符串为对象数组 const fileRead = JSON.parse(fileContent); // 转换为表格结构 const tableData = { headers: ["Name", "Age"], rows: fileRead.map(row => [row.name, row.Age]) }; console.log(fileRead); // 输出解析后的JSON数组 console.log(tableData); // 输出表格结构数据
异步读取版本(更符合Node.js最佳实践)
const fs = require('fs').promises; async function loadTableData() { try { // 异步读取文件 const fileContent = await fs.readFile("/Users/mken/Desktop/Node JS/DATA-TABLE/public/files/data.json", 'utf8'); const fileRead = JSON.parse(fileContent); // 生成表格结构 const tableData = { headers: ["Name", "Age"], rows: fileRead.map(row => [row.name, row.Age]) }; console.log(tableData); return tableData; } catch (error) { console.error('处理文件时出错:', error); } } loadTableData();
内容的提问来源于stack exchange,提问作者Ken
相关产品推荐
相关产品推荐

