You need to enable JavaScript to run this app. Node.js读取含#前缀行的JSON文件报语法错误的实现咨询
优惠活动
大模型
产品
解决方案
定价
更多

Node.js读取含#前缀行的JSON文件报语法错误的实现咨询

Node.js 非标准JSON文件读取实现方案

实现思路

  • 逐行拆分文件内容,将#开头的行与正文类JSON内容分离
  • 从#开头的行中提取键值对,生成独立配置对象
  • 通过正则规则将无引号的类JSON内容修正为合法JSON格式,再调用JSON.parse完成解析
  • 全程仅使用Node.js内置fs、path模块,无第三方依赖

完整实现代码

const fs = require('fs');
const path = require('path');

/**
 * 将松散类JSON格式转换为合法可解析的JSON字符串
 * @param {string} looseStr 无引号键名、无引号字符串值的类JSON内容
 * @returns {string} 合法JSON字符串
 */
function normalizeLooseJSON(looseStr) {
  let result = looseStr.trim();
  // 为无引号的键名添加双引号
  result = result.replace(/([{,]\s*)([a-zA-Z0-9_$]+)\s*:/g, '$1"$2":');
  // 为无引号的字符串值添加双引号,保留数字、布尔值、null的原生类型
  result = result.replace(/:\s*([^0-9,\s{}][^,{}]*?)\s*([,}])/g, (match, val, suffix) => {
    const reservedWords = ['true', 'false', 'null'];
    if (reservedWords.includes(val.trim())) {
      return `: ${val}${suffix}`;
    }
    return `: "${val.trim()}"${suffix}`;
  });
  return result;
}

// 定义uploads目录路径
const uploadsDir = path.join(process.env.root_dir, 'uploads');
// 读取目录下所有文件,筛选目标测试文件
const targetFiles = fs.readdirSync(uploadsDir).filter(file => file.endsWith('.json'));

targetFiles.forEach(filename => {
  const filePath = path.join(uploadsDir, filename);
  // 以utf8编码读取文件原始内容
  const rawContent = fs.readFileSync(filePath, 'utf8');
  // 拆分行并过滤空行
  const lines = rawContent.split('\n').map(line => line.trim()).filter(line => line.length);

  // 分离#开头的配置行与正文内容行
  const configLines = [];
  const contentLines = [];
  lines.forEach(line => {
    line.startsWith('#') ? configLines.push(line) : contentLines.push(line);
  });

  // 解析配置对象
  const config = {};
  configLines.forEach(line => {
    // 移除行首#号,按第一个冒号拆分键值(支持值中包含冒号的场景)
    const configStr = line.slice(1).trim();
    const [key, value] = configStr.split(/:(.*)/s);
    if (key && value) {
      config[key.trim()] = value.trim();
    }
  });

  // 处理类JSON正文内容
  const looseJSONContent = contentLines.join('');
  const validJSONStr = normalizeLooseJSON(looseJSONContent);
  const jsonData = JSON.parse(validJSONStr);

  // 最终输出结果:配置对象 + 解析的JSON数据
  console.log('提取的配置对象:', config);
  console.log('解析的JSON数据:', jsonData);
});

效果验证

针对题目中给出的测试文件格式:

  • 头部3行配置#PATH:/test/、#DEVICES:div1、#TYPE:p1会被提取为配置对象{PATH: '/test/', DEVICES: 'div1', TYPE: 'p1'}
  • 剩余的无引号类JSON内容会被自动修正为带双引号的合法JSON格式,可被JSON.parse正常解析,不会再触发Unexpected token类报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.23 03:36:02