我可以在json文件里使用注释吗? 如果是的话,怎么写?


当前回答

如果您以文本文件的形式装入, 您可以使用带有注释的 json , 然后删除注释 。

例如,您可以为此使用 decomment 库。下面是一个完整的示例。

输入json (文件输入.js) :

/*
* multi-line comments
**/
{
    "value": 123 // one-line comment
}

测试应用程序 :

var decomment = require('decomment');
var fs = require('fs');

fs.readFile('input.js', 'utf8', function (err, data) {
    if (err) {
        console.log(err);
    } else {
        var text = decomment(data); // removing comments
        var json = JSON.parse(text); // parsing JSON
        console.log(json);
    }
});

输出 :

{ value: 123 }

ưμ㼯A

其他回答

如果您的上下文是节点. js 配置, 您可以考虑通过模块使用 javascript 。 exports 作为json 的替代 :

module.exports = {
    "key": "value",

    // And with comments!
    "key2": "value2"
};

需要的语法将保持不变。 作为 javascript, 文件扩展名应该是 .js 。

json不支持评论,也从未打算用于需要评论的配置文件。

hjson 是人类的配置文件格式。 放松语法, 减少错误, 更多评论 。

图书馆、java、python、php、生锈、走、红宝石、C+++和c图书馆见hjson.github.io。

因此我将调试信息放入 http 网站页眉, 以避免打破客户端:

header("My-Json-Comment: Yes, I know it's a workaround ;-) ");

至少这是我在Json. org的一眼 所经历的

json的语法在那一页上被视觉化了。

(hack)是一个很好的解决办法(hack),这是有效的json,但并非在所有情况下都能奏效(见下文的评论)。

{
  "param" : "This is the comment place",
  "param" : "This is value place",
}

所以json会理解这一点:

{
  "param" : "This is value place",
}