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


当前回答

这是我在Google Firebbase文档中找到的东西, 可以让你在json中发表评论:

{
  "//": "Some browsers will use this to enable push notifications.",
  "//": "It is the same for all projects, this is not your project's sender ID",
  "gcm_sender_id": "1234567890"
}

其他回答

确定您可以对 json 进行评论。 从 javascript 读取 json 注释文件, 您可以在解析前删除评论( 参见下面的代码) 。 我确信这个代码可以改进, 但对于使用常规表达式的人来说很容易理解 。

我使用备受评论的json文件来指定我的合成反射系统 的神经元形状。 我也使用备受评论的json 来储存一个运行中的神经元系统的中间状态。 方便地得到评论。 不要听那些告诉你他们是个坏主意的人。

fetch(filename).then(function(response) {
    return response.text();
}).then(function(commented) {
    return commented.
        replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1').
        replace(/\r/,"\n").
        replace(/\n[\n]+/,"\n");
}).then(function(clean) {
    return JSON.parse(clean);
}).then(function(json) {
    // Do what you want with the JSON object.
});

如果您使用 json5, 您可以包含注释 。


json5建议扩展至json, 目的是使人类更容易手写和保持。

在json中不允许使用表格///...或/*...* /的注释。

https://www.json.org rfc 4627: Javacampn 对象标记(json)申请/json媒体类型(json) rfc 8259; json) 数据交换格式(supercedes rfcs 4627, 7158, 7159)

纯粹的答案是否定的。

但有些编辑和平台使用变通办法来补充json的评论。

1. 今天,大多数编辑都有内置选项和扩展选项,以对json文件添加评论。 (例如:- vs code 也有一个带有评论(jsonc) 模式/ vs code 的json 也有一个漂亮的扩展)

在 vscode 中激活 jsonc 模式的链接

2. 有些平台提供内置方式来补充评论(简洁json)。 (例如:-在消防基地,我可以对消防基地.jsons发表一段没有问题的评论。)

    {
    "hosting": {
        "headers": [
            /*{
              "source": "*.html",
              "headers": [
                {
                  "key": "Content-Security-Policy",
                  "value": "default-src 'self' ..."
                }
              ]
            },*/
        ]
      }
    }

3. 在你自己的json 解析方法中,您可以设置一个预定义的密钥名作为注释。

包括:-

     {
        "comment" : "This is a comment",
        "//" :  "This also comment",
        "name" : "This is a real value"
     }

您可以使用 json-ld 和 schema.org 批注类型来正确写备注:

{
    "https://schema.org/comment": "this is a comment"
}