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


当前回答

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

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

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

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

其他回答

在我目前的项目中,我遇到了这个问题, 因为我有相当多的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
}
"""))

是的,你可以,但你的分析可能会失败(没有标准)。

要进行剖析,您应该删除这些注释,或者通过手写,或者使用正则表达式:

它替换任何评论,例如:

/****
 * Hey
 */

/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/

它替换任何评论,例如:

// Hey

/\/\/.*/

你可以做这样的事情:

jsonString = jsonString.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/, "").replace(/\/\/.*/,"")
var object = JSON.parse(jsonString);

它取决于您的 json 库。json.net 支持 javascamps 风格的评论,/ * 逗号 * / 。

见另一个堆叠溢出的问题。

你可以在jsonp中发表评论,但不能在纯json中发表评论。 我只是花了一个小时试图用这个高雅的图表来做我的节目。

如果你遵循链接,你将看见

?(/* AAPL historical OHLC data from the Google Finance API */
[
/* May 2006 */
[1147651200000,67.79],
[1147737600000,64.98],
...
[1368057600000,456.77],
[1368144000000,452.97]
]);

我本地文件夹里也有类似的文件, 与同一来源的政策没有问题, 所以我决定使用纯json... 当然,$. Getjson因为评论而沉默不语。

我最后向上述地址发送了一份手册 http 请求, 并意识到内容类型是文本/ javascript, 因为, jsonp 返回纯正的 javascript 。 在此情况下, 批注是允许的 。 但我的应用程序返回了内容类型应用程序/ json, 所以我不得不删除批注 。

叹息。为什么不只添加字段,例如:

{
    "note1" : "This demonstrates the provision of annotations within a JSON file",
    "field1" : 12,
    "field2" : "some text",

    "note2" : "Add more annotations as necessary"
}

只要确保你的"笔记本"名字 不与任何真实的字段冲突。