gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:40:42 26 4
gpt4 key购买 nike

我如何读取这个文件“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 一些包来解决这个问题吗?

最佳答案

这个问题的完美包是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);

关于javascript - 读取 json 文件忽略自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com