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

如何在客户端JavaScript中解析带注释的JSON文件?无需保留注释

纯客户端移除JSON注释并解析的方案

核心思路

放弃直接用$.getJSON请求,先获取文件的原始文本,移除注释后再解析成合法的JSON对象。

步骤1:获取JSON文件的原始文本

用$.get替代$.getJSON,指定获取纯文本内容:

$.get('file.json', function(rawText) {
  // 后续处理注释并解析
}, 'text');

步骤2:编写注释移除函数

这个函数可以处理单行//注释和多行/* */注释,同时不会误删字符串内部的类似字符(比如"//这是字符串内容"不会被当成注释):

function removeJsonComments(jsonText) {
  let inString = false;
  let inBlockComment = false;
  const result = [];
  let i = 0;

  while (i < jsonText.length) {
    const char = jsonText[i];
    const nextChar = jsonText[i+1] || '';

    // 处理字符串边界,跳过转义的引号
    if (char === '"' && !inBlockComment) {
      if (i > 0 && jsonText[i-1] === '\\') {
        result.push(char);
      } else {
        inString = !inString;
        result.push(char);
      }
      i++;
      continue;
    }

    // 处理块注释的开始和结束
    if (!inString && char === '/' && nextChar === '*') {
      inBlockComment = true;
      i += 2;
      continue;
    }
    if (inBlockComment && char === '*' && nextChar === '/') {
      inBlockComment = false;
      i += 2;
      continue;
    }

    // 处理单行注释,跳过到行尾
    if (!inString && !inBlockComment && char === '/' && nextChar === '/') {
      while (i < jsonText.length && jsonText[i] !== '\n') {
        i++;
      }
      continue;
    }

    // 非注释字符加入结果
    if (!inBlockComment) {
      result.push(char);
    }
    i++;
  }

  return result.join('');
}

步骤3:解析处理后的文本

将移除注释后的文本用JSON.parse解析成JSON对象:

$.get('file.json', function(rawText) {
  try {
    const cleanedText = removeJsonComments(rawText);
    const jsonData = JSON.parse(cleanedText);
    // 这里编写你的业务逻辑
    console.log(jsonData);
  } catch (error) {
    console.error('JSON处理失败:', error);
  }
}, 'text');

注意事项

  • 该函数能覆盖绝大多数普通注释场景,对于非技术人员编辑的简单JSON文件完全够用;如果遇到极端复杂的转义字符串,可能需要微调逻辑。
  • 要确保移除注释后的文本是合法JSON,比如注释不要破坏原有JSON的结构(比如不要在键值对中间遗留无效字符)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:31:43