读取 json 文件,忽略自定义注释

Read json file ignoring custom comments

如何读取这个文件'file.json':

# Comment01
# Comment02
{
   "name": "MyName"
}

并在没有评论的情况下检索 json?

我正在使用此代码:

var fs = require('fs');
var obj;
fs.readFile('./file.json', 'utf8', function (err, data) { 
  if (err) throw err;
  obj = JSON.parse(data);
});

它returns这个错误:

SyntaxError: Unexpected token # in JSON at position 0

npm 一些包来解决这个问题吗?

您要查找的包名为 strip-json-comments - https://github.com/sindresorhus/strip-json-comments

const json = '{/*rainbows*/"unicorn":"cake"}';

JSON.parse(stripJsonComments(json)); //=> {unicorn: 'cake'}

您可以使用自己的 RegExp 非常轻松地匹配以 #

开头的评论
const matchHashComment = new RegExp(/(#.*)/, 'gi');
const fs = require('fs');

fs.readFile('./file.json', (err, data) => {
    // replaces all hash comments & trim the resulting string
    let json = data.toString('utf8').replace(matchHashComment, '').trim();  
    json = JSON.parse(json);
    console.log(json);
});

这个问题的完美解决方案是https://www.npmjs.com/package/hjson

hjson文本输入:


{
  # hash style comments
  # (because it's just one character)

  // line style comments
  // (because it's like C/JavaScript/...)

  /* block style comments because
     it allows you to comment out a block */

  # Everything you do in comments,
  # stays in comments ;-}
}

用法:

var Hjson = require('hjson');

var obj = Hjson.parse(hjsonText);
var text2 = Hjson.stringify(obj);

NPM 上有替代包:json-easy-strip 主要思想是仅使用一行 RegExp 来去除所有类型的 JS 样式注释。是的,这很简单而且很有可能!包更高级,有一些文件缓存等,但仍然很简单。这是核心:

sweet.json

{
    /*
     * Sweet section
     */
    "fruit": "Watermelon", // Yes, watermelons is sweet!
    "dessert": /* Yummy! */ "Cheesecake",
    // And finally
    "drink": "Milkshake - /* strawberry */ or // chocolate!" // Mmm...
}

index.js

const fs = require('fs');
const data = (fs.readFileSync('./sweet.json')).toString();

// Striper core intelligent RegExp.
// The idea is to match data in quotes and
// group JS-type comments, which is not in
// quotes. Then return nothing if there is
// a group, else return matched data.
const json = JSON.parse(data.replace(/\"|"(?:\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m));

console.log(json);

//  {
//    fruit: 'Watermelon',
//    dessert: 'Cheesecake',
//    drink: 'Milkshake - /* strawberry */ or // chocolate!'
//  }

所以现在因为你问的是 ShellScripting 风格的评论

#
# comments
#

我们可以通过在其末尾添加 \#.* 来扩展我们的 RegExp:

const json = JSON.parse(data.replace(/\"|"(?:\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/|\#.*)/g, (m, g) => g ? "" : m));

或者,如果您根本不想要 JS 样式的注释:

const json = JSON.parse(data.replace(/\"|"(?:\"|[^"])*"|(\#.*)/g, (m, g) => g ? "" : m));

Javascript 有一个评论删除器 built-in,不需要额外的包。不过,我不会为用户输入这样做。

eval(
  'var myjsonfile=' +
    require('fs')
      .readFileSync('./myjsonfile.json')
      .toString(),
);
console.log(myjsonfile);