You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js复制JSON文件后读取结果为字符串,无法访问JSON属性怎么办?

问题原因与解决方案

原因

使用fs.readFile并指定utf8编码时,Node.js只会返回文件的原始字符串内容——复制文件的操作只是原样拷贝字节数据,不会自动将JSON格式的字符串解析为JavaScript对象。因此你拿到的data是JSON字符串,而非可直接访问属性的对象,自然无法调用data.Data.users。

解决方案

读取到字符串后,需要手动用JSON.parse()将其解析为JavaScript对象。以下是几种可行的实现方式:

1. 回调式读取+JSON解析

const fs = require('fs');

fs.copyFile('user/access.json', 'client/access.json', (copyErr) => {
  if (copyErr) throw copyErr;
  
  fs.readFile('client/access.json', 'utf8', (readErr, data) => {
    if (readErr) throw readErr;
    
    try {
      // 将JSON字符串解析为对象
      const jsonData = JSON.parse(data);
      console.log(jsonData.Data.users); // 正常访问属性
    } catch (parseErr) {
      console.error('JSON解析失败,请检查文件格式:', parseErr);
    }
  });
});

2. 使用require直接加载JSON文件

require会自动解析JSON文件并返回对象,但要注意它会缓存文件内容,如果后续修改了目标JSON文件,再次调用require不会读取最新内容:

const fs = require('fs');

fs.copyFile('user/access.json', 'client/access.json', (err) => {
  if (err) throw err;
  
  // require自动解析JSON为对象
  const jsonData = require('./client/access.json');
  console.log(jsonData.Data.users);
});

3. Promise/Async-Await风格(推荐现代项目使用)

const fs = require('fs').promises;

async function handleCopyAndRead() {
  try {
    await fs.copyFile('user/access.json', 'client/access.json');
    const data = await fs.readFile('client/access.json', 'utf8');
    const jsonData = JSON.parse(data);
    console.log(jsonData.Data.users);
  } catch (err) {
    console.error('操作失败:', err);
  }
}

handleCopyAndRead();

内容的提问来源于stack exchange,提问作者Arun Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:15:33