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


当前回答

json 规格不支持评论, // 或/ * * / 样式。

但一些 Json 剖析图书馆和助手支持它们。

类似 :

json5 视觉演播室 代码评论

其他回答

在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 。

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

2019年视觉演播室代码用户的实际答案是使用“jsonc”扩展名。

这是切合实际的,因为这是视像工作室代码所认可的延伸,表示“Json带评论”,请让我了解下文评论中的其他编辑/旁听者。

如果视觉演播室代码和其他编辑也加入本地对Json5的支持, 那将会是件好事, 但现在视觉演播室代码只包括“jsonc”的支持。

(我在张贴前搜索了所有答案,

这是一个"你能"的问题。 这是"可以"的答案。

否, 您不应该使用重复对象成员将侧通道数据塞进json 编码 。 (请参见 rfc 中“ 对象中的名称应该是独一无二的 ” ) 。

是的,你可以在json周围插入评论, 你可以分析出来。

但如果你想将任意的侧道数据插入和提取到一个有效的json 中, 请使用一个答案 。 我们利用 Json 编码中的数据非独有的表达方式。 在 rfc 的第二节中, “ 允许在六个结构字符中的任何字符之前或之后使用白色空间 ” 。

* rfc 仅表示“在六个结构字符之前或之后允许有白色空间”,但没有明确提及字符串、数字、“假”、“真”和“null”。 在所有执行中,这一遗漏被忽略。


首先,将你的json拼写成拼写:

$jsonMin = json_encode(json_decode($json));

然后将您的评论编码为二进制 :

$hex = unpack('H*', $comment);
$commentBinary = base_convert($hex[1], 16, 2);

然后输入您的二进制 :

$steg = str_replace('0', ' ', $commentBinary);
$steg = str_replace('1', "\t", $steg);

您的输出 :

$jsonWithComment = $steg . $jsonMin;