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

w8rqjzmb  于 2023-01-08  发布在  Node.js
关注(0)|答案(6)|浏览(241)

我如何读取这个文件'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);
});

则返回以下错误:

SyntaxError: Unexpected token # in JSON at position 0

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

wqlqzqxt

wqlqzqxt1#

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);
8iwquhpp

8iwquhpp2#

您可以很容易地使用自己的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);
});
5n0oy7gb

5n0oy7gb3#

关于国家预防机制,有备选方案: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));
r7knjye2

r7knjye24#

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

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

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

s4chpxco5#

let json = require('json5')
let fs = require('fs-extra')

let a = json.parse(fs.readFileSync("./tsconfig.json"))
console.log(a)

您可以使用json5模块

zqdjd7g9

zqdjd7g96#

Javascript有一个内置的注解移除器,不需要额外的软件包。不过我不会为用户输入做这个。

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

相关问题