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


当前回答

在json中需要评论,并且至少可在.net核心json 和 tonosojson 中提供评论。

{
  // this is a comment for those who is ok with being different
  "regular-json": "stuff"...
}

其他回答

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

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

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

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

注释不是官方标准,尽管有些分析者支持 c++- 风格的注释。

// Configuration options
{
    // Default encoding for text
    "encoding" : "UTF-8",

    // Plug-ins loaded at start-up
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],

    // Tab indent size
    "indent" : { "length" : 3, "use_space": true }
}

jsonlint 不验证这一点 。 因此, 批注是解析器特定的扩展名, 而不是标准 。

另一本书是Json5。

取代json Toml的替代品。

另一种选择是jsonc。

Nlohmann/json的最新版本有选择的支持,

在我目前的项目中,我遇到了这个问题, 因为我有相当多的json 需要一些评论 使事情容易记住。

i've used this simple python 函数来替换批注并使用 json. loads 将其转换成 dict:

import json, re

def parse_json(data_string):
  result = []
  for line in data_string.split("\n"):
    line = line.strip()
    if len(line) < 1 or line[0:2] == "//":
      continue
    if line[-1] not in "\,\"\'":
      line = re.sub("\/\/.*?$", "", line)
    result.append(line)
  return json.loads("\n".join(result))

print(parse_json("""
{
  // This is a comment
  "name": "value" // so is this
  // "name": "value"
  // the above line gets removed
}
"""))

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

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

正如许多答案已经指出的,Json在本地没有评论。当然,有时你还是想要评论。对python来说,两种方法就是评论json(和//仅对python 2)或json_tricks(或//对python 2和python 3),这有其他几个特点。免责声明:我做了json_tricks。