NPM 上有替代包:json-easy-strip
主要思想是只使用单行 RegExp 来剥离所有类型的 JS 风格的 cmets。是的,这很简单而且很有可能!包更高级,有一些文件缓存等,但仍然很简单。这是核心:
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 样式的 cmets
#
# comments
#
我们可以通过在其末尾添加\#.* 来扩展我们的正则表达式:
const json = JSON.parse(data.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/|\#.*)/g, (m, g) => g ? "" : m));
或者,如果你根本不想要 JS 风格的 cmets:
const json = JSON.parse(data.replace(/\\"|"(?:\\"|[^"])*"|(\#.*)/g, (m, g) => g ? "" : m));