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


当前回答

您应该撰写json schema。json schema目前是一份拟议互联网规格草案。除文档外,该schema还可以用于验证您的json数据 。

例如:

{
  "description": "A person",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer",
      "maximum": 125
    }
  }
}

您可以使用描述 schema 属性提供文档。

其他回答

纯粹的答案是否定的。

但有些编辑和平台使用变通办法来补充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"
     }

在撰写本报告时,Appings.json支持评论。

例如(微软的样本)

{
  "Logging": {
    "LogLevel": { // All providers, LogLevel applies to all the enabled providers.
      "Default": "Error", // Default logging, Error and higher.
      "Microsoft": "Warning" // All Microsoft* categories, Warning and higher.
    },
    "Debug": { // Debug provider.
      "LogLevel": {
        "Default": "Information", // Overrides preceding LogLevel:Default setting.
        "Microsoft.Hosting": "Trace" // Debug:Microsoft.Hosting category.
      }
    },
    "EventSource": { // EventSource provider
      "LogLevel": {
        "Default": "Warning" // All categories of EventSource provider.
      }
    }
  }
}

虽然json不支持评论,jsonc支持。

使用 jsonc 剖析器 。 抱歉, 如果回答为时已晚, 请将您的文件命名为“. jsonc ” 扩展名, 并使用 jsonc 剖析器 。

jsonWithComments.jsonc

例如:

{
    // This is a comment!
    "something": "idk"

}

如果这还不清楚, 我认为机器人是奇怪的。 请在投票前先试一下, 这个问题没有帮助 。

注释中包括您选择的注释;在解析或传输之前用一个分解符将其删除。

i 刚刚发布json.minify () , 它将评论和空白从json区块中分离出来, 并使它成为有效的json, 可以进行剖析。 所以, 您可以使用它 :

JSON.parse(JSON.minify(my_str));

所以我决定写一篇全面的博客文章, 说明为什么评论在json中有意义。

假设您正在使用 json 来保存配置文件, 您想要对这些文件进行注释。 请继续插入您想要的所有评论。 然后通过 jsmin 进行管道, 然后将它交给您的 Jsson 采集器 。 - Douglas crockford, 2012 。

希望这对不同意Json. minify()的原因的人会有帮助。

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

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

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

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